Byte array to hex python

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.

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Sometimes, we might be in a problem in which we need to handle unusual Datatype conversions. One such conversion can be converting the list of bytes(byte array) to the Hexadecimal string format in Python. Let’s discuss certain Methods in which this can be done. 

    Using format() + join()  to Convert Byte Array to Hex String

    The combination of the above functions can be used to perform this particular task. The format function converts the bytes into hexadecimal format. “02” in format is used to pad required leading zeroes. The join function allows joining the hexadecimal result into a string. 

    Python3

    test_list = [124, 67, 45, 11]

    print("The original string is : " + str(test_list))

    res = ''.join(format(x, '02x') for x in test_list)

    print("The string after conversion : " + str(res))

    Output:

    The original string is : [124, 67, 45, 11]
    The string after conversion : 7c432d0b

    Using binascii.hexlify() to convert Byte Array to Hex String

    The inbuilt function of hexlify can be used to perform this particular task. This function is recommended for this particular conversion as it is tailor-made to solve this specific problem. 

    Python3

    import binascii

    test_list = [124, 67, 45, 11]

    print("The original string is : " + str(test_list))

    res = binascii.hexlify(bytearray(test_list))

    print("The string after conversion : " + str(res))

    Output:

    The original string is : [124, 67, 45, 11]
    The string after conversion : 7c432d0b

    RECOMMENDED ARTICLES – Python | bytearray() function


    How to convert a byte array to hex string in Python?

    Use bytearray..
    byte_array = bytearray(b"\xab").
    hexadecimal_string = byte_array. hex().
    print(hexadecimal_string).

    How to convert byte to hex Python?

    Use the hex() Method to Convert a Byte to Hex in Python The hex() method introduced from Python 3.5 converts it into a hexadecimal string. In this case, the argument will be of a byte data type to be converted into hex.

    How do you convert bytes to hexadecimal?

    Java Programs to Convert Byte to Hexadecimal.
    public class ByteToHex1..
    public static void main(String args[]).
    byte num = (byte)4556;.
    System.out.println("Byte = "+num);.
    int hex = num & 0xFF;.
    System.out.println("Hexadecimal Equivalent= "+Integer.toHexString(hex));.

    How do you declare a hex string in Python?

    Python hex() function is used to convert an integer to a lowercase hexadecimal string prefixed with “0x”. We can also pass an object to hex() function, in that case the object must have __index__() function defined that returns integer. The input integer argument can be in any base such as binary, octal etc.