bytearray – hexadecimal string to byte array in python

bytearray – hexadecimal string to byte array in python

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
xdexadxbexef

or since Python 2.7 and Python 3.0:

>>> bytes.fromhex(hex_string)  # Python ≥ 3
bxdexadxbexef

>>> bytearray.fromhex(hex_string)
bytearray(bxdexadxbexef)

Note that bytes is an immutable version of bytearray.

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.

bytearray – hexadecimal string to byte array in python

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]

Leave a Reply

Your email address will not be published. Required fields are marked *