231

I have a long Hex string that represents a series of values of different types. I need to convert this Hex String into bytes or bytearray so that I can extract each value from the raw data. How can I do this?

For example, the string "ab" should convert to the bytes b"\xab" or equivalent byte array. Longer example:

>>> # what to use in place of `convert` here?
>>> convert("8e71c61de6a2321336184f813379ec6bf4a3fb79e63cd12b")
b'\x8eq\xc6\x1d\xe6\xa22\x136\x18O\x813y\xeck\xf4\xa3\xfby\xe6<\xd1+'
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
Richard
  • 15,152
  • 31
  • 85
  • 111

7 Answers7

378

Suppose your hex string is something like

>>> hex_string = "deadbeef"

Convert it to a bytearray (Python 3 and 2.7):

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

Convert it to a bytes object (Python 3):

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

Note that bytes is an immutable version of bytearray.

Convert it to a string (Python ≤ 2.7):

>>> hex_data = hex_string.decode("hex")
>>> hex_data
"\xde\xad\xbe\xef"
wjandrea
  • 28,235
  • 9
  • 60
  • 81
tzot
  • 92,761
  • 29
  • 141
  • 204
  • 7
    **Note** that `bytes.fromhex` throws an error when the input string has an odd number of characters: `bytes.fromhex("aab")` → `ValueError: non-hexadecimal number found in fromhex() arg at position 3`. – Константин Ван Jul 24 '18 at 17:35
  • 1
    The new version of `hex_string.decode("hex")` is `codecs.decode(hex_string, 'hex')`. – wjandrea Jun 30 '22 at 19:42
165

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.

kugg
  • 1,727
  • 1
  • 10
  • 5
20

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

import binascii
a='45222e'
s=binascii.unhexlify(a)
b=[ord(x) for x in s]
Bruce
  • 7,094
  • 1
  • 25
  • 42
  • 4
    I agree that `unhexlify` is the most efficient way to go here, but would suggest that `b = bytearray(s)` would be a better than using `ord`. As Python has a built-in type just for arrays of bytes I'm surprised no one is using it – Scott Griffiths Apr 13 '11 at 15:03
8

Assuming you have a byte string like so

"\x12\x45\x00\xAB"

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('<BBH', bytes)

#val = (18, 69, 43776)

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

Disadvantages..

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

Hovo
  • 455
  • 4
  • 9
  • 2
    Disadvantages: that is a byte string, not a hex string, so this is not an answer to the question. – qris Feb 06 '15 at 13:29
  • 1
    It is an answer to the 2nd part of the question "... so that I can shift each value out and convert it into its proper data type". – Rainald62 May 06 '19 at 16:02
2

You can use the Codecs module in the Python Standard Library, i.e.

import codecs

codecs.decode(hexstring, 'hex_codec')
varantir
  • 6,624
  • 6
  • 36
  • 57
velsim
  • 553
  • 1
  • 7
  • 17
0

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.

unwind
  • 391,730
  • 64
  • 469
  • 606
-7

A good one liner is:

byte_list = map(ord, hex_string)

This will iterate over each char in the string and run it through the ord() function. Only tested on python 2.6, not too sure about 3.0+.

-Josh

karlw
  • 668
  • 4
  • 13