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 ]
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 ]
Using
str.format
:or using
format
or using
bytearray
withbinascii.hexlify
:Here is a benchmark of above methods in Python 3.6.1:
Result:
Methods using
format
do provide additional formatting options, as example separating numbers with spaces" ".join
, commas", ".join
, upper-case printing"{:02X}".format(x)
/format(x, "02X")
, etc., but at a cost of great performance impact.If you have a numpy array, you can do the following:
Or, if you are a fan of functional programming:
Consider the hex() method of the
bytes
type on Python 3.5 and up:EDIT: it's also much faster than
hexlify
(modified @falsetru's benchmarks above)Result: