0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0
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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.