Reputation: 15862
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+'
Upvotes: 254
Views: 610768
Reputation: 95901
Suppose your hex string is something like
>>> hex_string = "deadbeef"
>>> bytearray.fromhex(hex_string)
bytearray(b'\xde\xad\xbe\xef')
>>> bytes.fromhex(hex_string)
b'\xde\xad\xbe\xef'
Note that bytes
is an immutable version of bytearray
.
>>> hex_data = hex_string.decode("hex")
>>> hex_data
"\xde\xad\xbe\xef"
Upvotes: 413
Reputation: 583
You can use the Codecs module in the Python Standard Library, i.e.
import codecs
codecs.decode(hexstring, 'hex_codec')
Upvotes: 2
Reputation: 1775
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.
Upvotes: 168
Reputation: 454
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
Upvotes: 8
Reputation: 399703
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.
Upvotes: 0
Reputation: 7132
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]
Upvotes: 20
Reputation: 668
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
Upvotes: -7