Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks for the help!

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading