I have data stored in a byte array. How can I convert this data into a hex string?
Example of my byte array:
array_alpha = [ 133, 53, 234, 241 ]
This question is related to
python
string
python-2.7
bytearray
Consider the hex() method of the bytes
type on Python 3.5 and up:
>>> array_alpha = [ 133, 53, 234, 241 ]
>>> print(bytes(array_alpha).hex())
8535eaf1
EDIT: it's also much faster than hexlify
(modified @falsetru's benchmarks above)
from timeit import timeit
N = 10000
print("bytearray + hexlify ->", timeit(
'binascii.hexlify(data).decode("ascii")',
setup='import binascii; data = bytearray(range(255))',
number=N,
))
print("byte + hex ->", timeit(
'data.hex()',
setup='data = bytes(range(255))',
number=N,
))
Result:
bytearray + hexlify -> 0.011218150997592602
byte + hex -> 0.005952142993919551
If you have a numpy array, you can do the following:
>>> import numpy as np
>>> a = np.array([133, 53, 234, 241])
>>> a.astype(np.uint8).data.hex()
'8535eaf1'
Or, if you are a fan of functional programming:
>>> a = [133, 53, 234, 241]
>>> "".join(map(lambda b: format(b, "02x"), a))
8535eaf1
>>>
hex_string = "".join("%02x" % b for b in array_alpha)
Source: Stackoverflow.com