0


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: \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00...

Thanks for the help!

Bar Ifrah
  • 80
  • 7
  • https://stackoverflow.com/questions/6624453/whats-the-correct-way-to-convert-bytes-to-a-hex-string-in-python-3 – johann May 21 '22 at 09:36

2 Answers2

2

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)
\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x21
tevemadar
  • 12,389
  • 3
  • 21
  • 49
1

Use binascii

import binascii

value = "hello world"
print(binascii.hexlify(value.encode("utf-8")))  # b'68656c6c6f20776f726c64'
print(binascii.unhexlify(b'68656c6c6f20776f726c64').decode())  # hello world

print('\x68\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64')  # hello world
azro
  • 53,056
  • 7
  • 34
  • 70