'I want to convert a hexadecimal byte array to hexadecimal in string format

I want to convert byte format to string format. The conversion target is as follows. \xb9S\xfc\x81\xe4\xa2\xb9\x92\x8d\xbb1\xfe\xb9\xa1&\x16\ ...... Convert to string format.

For example, b'\xfc\x81\xe4\xa2\xb9\x92' #type:bytes -> "FC 81 E4 A2 B9 92" #type:str

No matter how much I searched, I couldn't find the module by myself. Any help would be appreciated.



Solution 1:[1]

def format_bytes_as_hex(b: bytes) -> str:
    h = b.hex()
    return ' ' .join(f'{a}{b}'.upper() for a, b in zip(h[0::2], h[1::2]))


Test:
format_bytes_as_hex(b'\xfc\x81\xe4\xa2\xb9\x92')
'FC 81 E4 A2 B9 92'

Solution 2:[2]

This is implemented in the standard lib

Starting with python 3.5, you got this :

val = b'AAAAA'
print(val.hex())
    
# prints '4141414141'

With python 3.8+, you can also specify a separator :

val = b'AAAAA'
print(val.hex(' '))
    
# prints '41 41 41 41 41'

if you absolutely want them in uppercase, you can call upper() on the result.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tom McLean
Solution 2 A-y