Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte Array to Hex String

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 ] 
like image 461
Jamie Wright Avatar asked Oct 06 '13 15:10

Jamie Wright


People also ask

How do you convert bytes to hexadecimal?

To convert byte array to a hex value, we loop through each byte in the array and use String 's format() . We use %02X to print two places ( 02 ) of Hexadecimal ( X ) value and store it in the string st . This is a relatively slower process for large byte array conversion.

How many hex is 4 bytes?

Byte to Hexadecimal. The bytes are 8 bit signed integers in Java. Therefore, we need to convert each 4-bit segment to hex separately and concatenate them. Consequently, we'll get two hexadecimal characters after conversion.

How big is a byte in hex?

So a byte -- eight binary digits -- can always be represented by two hexadecimal digits.

What is a Hexstring?

Hexadecimal Number String. The “Hexadecimal” or simply “Hex” numbering system uses the Base of 16 system and are a popular choice for representing long binary values because their format is quite compact and much easier to understand compared to the long binary strings of 1's and 0's.


2 Answers

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 
like image 41
orip Avatar answered Oct 18 '22 19:10

orip


Using str.format:

>>> array_alpha = [ 133, 53, 234, 241 ] >>> print ''.join('{:02x}'.format(x) for x in array_alpha) 8535eaf1 

or using format

>>> print ''.join(format(x, '02x') for x in array_alpha) 8535eaf1 

Note: In the format statements, the 02 means it will pad with up to 2 leading 0s if necessary. This is important since [0x1, 0x1, 0x1] i.e. (0x010101) would be formatted to "111" instead of "010101"

or using bytearray with binascii.hexlify:

>>> import binascii >>> binascii.hexlify(bytearray(array_alpha)) '8535eaf1' 

Here is a benchmark of above methods in Python 3.6.1:

from timeit import timeit import binascii  number = 10000  def using_str_format() -> str:     return "".join("{:02x}".format(x) for x in test_obj)  def using_format() -> str:     return "".join(format(x, "02x") for x in test_obj)  def using_hexlify() -> str:     return binascii.hexlify(bytearray(test_obj)).decode('ascii')  def do_test():     print("Testing with {}-byte {}:".format(len(test_obj), test_obj.__class__.__name__))     if using_str_format() != using_format() != using_hexlify():         raise RuntimeError("Results are not the same")      print("Using str.format       -> " + str(timeit(using_str_format, number=number)))     print("Using format           -> " + str(timeit(using_format, number=number)))     print("Using binascii.hexlify -> " + str(timeit(using_hexlify, number=number)))  test_obj = bytes([i for i in range(255)]) do_test()  test_obj = bytearray([i for i in range(255)]) do_test() 

Result:

Testing with 255-byte bytes: Using str.format       -> 1.459474583090427 Using format           -> 1.5809937679100738 Using binascii.hexlify -> 0.014521426401399307 Testing with 255-byte bytearray: Using str.format       -> 1.443447684109402 Using format           -> 1.5608712609513171 Using binascii.hexlify -> 0.014114164661833684 

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.

like image 180
falsetru Avatar answered Oct 18 '22 17:10

falsetru