hexadecimal string to byte array in python


Question

I have a long Hex string that represents a series of values of different types. I wish to convert this Hex String into a byte array so that I can shift each value out and convert it into its proper data type.

1
124
4/13/2011 2:23:18 PM

Accepted Answer

Suppose your hex string is something like

>>> hex_string = "deadbeef"

Convert it to a string (Python ≤ 2.7):

>>> hex_data = hex_string.decode("hex")
>>> hex_data
"\xde\xad\xbe\xef"

or since Python 2.7 and Python 3.0:

>>> bytes.fromhex(hex_string)  # Python ≥ 3
b'\xde\xad\xbe\xef'

>>> bytearray.fromhex(hex_string)
bytearray(b'\xde\xad\xbe\xef')

Note that bytes is an immutable version of bytearray.

192
7/25/2018 8:11:15 AM

There is a built-in function in bytearray that does what you intend.

bytearray.fromhex("de ad be ef 00")

It returns a bytearray and it reads hex strings with or without space separator.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon