hexadecimal string to byte array in python

Python Programming

Question or problem about Python programming:

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.

How to solve the problem:

Solution 1:

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
or since Python 2.7 and Python 3.0:
>>> bytes.fromhex(hex_string)  # Python ≥ 3

>>> bytearray.fromhex(hex_string)

Note that bytes is an immutable version of bytearray.

Solution 2:

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.

Solution 3:

provided I understood correctly, you should look for binascii.unhexlify

import binascii
b=[ord(x) for x in s]

Solution 4:

Assuming you have a byte string like so


and you know the amount of bytes and their type you can also use this approach

import struct

bytes = '\x12\x45\x00\xAB'
val = struct.unpack('

As I specified little endian (using the '<' char) at the start of the format string the function returned the decimal equivalent.

0x12 = 18

0x45 = 69

0xAB00 = 43776

B is equal to one byte (8 bit) unsigned

H is equal to two bytes (16 bit) unsigned

More available characters and byte sizes can be found here

The advantages are..

You can specify more than one byte and the endian of the values


You really need to know the type and length of data your dealing with

Solution 5:

You should be able to build a string holding the binary data using something like:

data = "fef0babe"
bits = ""
for x in xrange(0, len(data), 2)
  bits += chr(int(data[x:x+2], 16))

This is probably not the fastest way (many string appends), but quite simple using only core Python.

Hope this helps!