Skip to content
Advertisement

Represent string characters as hex values in python


I’m trying to represent a given string in hex values, and am failing.
I’ve tried this:

# 1
bytes_str = bytes.fromhex("hello world")

# 2
bytes_str2 = "hello world"
bytes_str2.decode('hex')

For the first one I get "ValueError: non-hexadecimal number found in fromhex() arg at position 0" error
For the second I get that there’s no decode attribute to str. It’s true but I found it here so I guessed it’s worth a shot.

My goal is to print a string like this: x00x00x00x00x00x00x00x00x00x00…

Thanks for the help!

Advertisement

Answer

bytes.fromhex() expects a string with hexadecimal digits inside, and possibly whitespace.
bytes.hex() is the one creating a string of hexadecimal digits from a byte object

>>> hello='Hello World!'                 # a string
>>> hellobytes=hello.encode()
>>> hellobytes
b'Hello World!'                          # a bytes object
>>> hellohex=hellobytes.hex()
>>> hellohex
'48656c6c6f20576f726c6421'               # a string with hexadecimal digits inside
>>> hellobytes2=bytes.fromhex(hellohex)  # a bytes object again
>>> hello2=hellobytes2.decode()          # a string again
>>> hello2
'Hello World!'                           # seems okay

However if you want an actual string with the x parts inside, you probably have to do that manually, so split the continuous hexstring into digit-pairs, and put x between them:

>>> formatted="\x"+"\x".join([hellohex[i:i + 2] for i in range(0, len(hellohex), 2)])
>>> print(formatted)
x48x65x6cx6cx6fx20x57x6fx72x6cx64x21
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement