Python Forum

Full Version: converting binary b'0x31303032\n' to "1002" string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I've tried so many things for hours with out success. Help would be so greatly appreciated.
I need to convert the binary type b'0x31303032\n' to "1002" string, which is the hexidecimal translation of 0x31303032
You can use binascii:
import binascii

x = b'0x31303032\n'
x1 = binascii.unhexlify(x.strip()[2:]).decode()
print(x1)
results:
Output:
1002
I should explain a bit:
binascii.unhexlify(hexstr)

Return the binary data represented by the hexadecimal string hexstr. This function is the inverse of b2a_hex(). hexstr must contain an even number of hexadecimal digits (which can be upper or lower case), otherwise an Error exception is raised.

x.strip() removes the line feed
the [2:] slices off the 0x
the decode() at the end flips from bytes
THANK YOU!
I was so close yet so far. Excellent work.