5 Best Ways to Convert Python Bytearray to Hex List

πŸ’‘ Problem Formulation: When working with binary data in Python, it is often necessary to convert a bytearray object into a list of hexadecimal strings for easier readability, storage, or further processing. For example, given the input bytearray(b'\x00\x0F\xF0'), the desired output would be the list ['00', '0f', 'f0']. This article will explore various methods to perform this conversion efficiently and effectively.

Method 1: Using a For Loop and format

An easy and straightforward method to convert a bytearray to a list of hexadecimal strings involves utilizing a for loop alongside the built-in format function.

Here’s an example:

byte_array = bytearray(b'\x00\x0F\xF0')
hex_list = [format(byte, '02x') for byte in byte_array]

print(hex_list)

Output:

['00', '0f', 'f0']

In this example, we iterate through each byte in the bytearray and use the format function with the ’02x’ format specifier, which converts a number to a two-character wide hexadecimal representation, including leading zeros. The list comprehension builds the hex list.

Method 2: Using the hex Method

The byte type in Python has a hex method that returns a string of hexadecimal numbers. However, to get a list of strings, further processing is required.

Here’s an example:

byte_array = bytearray(b'\x00\x0F\xF0')
hex_list = [byte.hex() for byte in byte_array]

print(hex_list)

Output:

['00', '0f', 'f0']

This code snippet uses a list comprehension to iterate through each byte in the bytearray, calling the hex method on each byte to get the hexadecimal representation. The returned strings are collected into a list.

Method 3: Using binascii.hexlify

For bytearrays, we can use the binascii.hexlify function from the binascii module to convert the whole bytearray into a single hexadecimal string, which then needs to be split into two-character chunks.

Here’s an example:

import binascii

byte_array = bytearray(b'\x00\x0F\xF0')
hex_str = binascii.hexlify(byte_array).decode('utf-8')
hex_list = [hex_str[i:i+2] for i in range(0, len(hex_str), 2)]

print(hex_list)

Output:

['00', '0f', 'f0']

The snippet above first converts the whole bytearray into a hexadecimal string using binascii.hexlify and then decodes it into a string. A list comprehension is then used to split this string into a list of two-character strings.

Method 4: Using bytes.hex with Slicing

Starting with Python 3.5, the bytes object received a hex method, which can be used similar to binascii.hexlify, but directly on a bytearray without importing additional modules.

Here’s an example:

byte_array = bytearray(b'\x00\x0F\xF0')
hex_string = byte_array.hex()
hex_list = [hex_string[i:i + 2] for i in range(0, len(hex_string), 2)]

print(hex_list)

Output:

['00', '0f', 'f0']

After getting a full hexadecimal string by calling byte_array.hex(), this code uses list comprehension with range slicing to create the final list of hex strings.

Bonus One-Liner Method 5: Using map with format

Sometimes a one-liner is what you need – a compact version using map and format can produce the same result as the first method.

Here’s an example:

byte_array = bytearray(b'\x00\x0F\xF0')
hex_list = list(map(lambda b: format(b, '02x'), byte_array))

print(hex_list)

Output:

['00', '0f', 'f0']

This method uses map to apply a lambda function that formats each byte in the bytearray using the ’02x’ formatter. We then convert the map object to a list to get the final hexadecimal list.

Summary/Discussion

  • Method 1: For Loop with format. Strengths: Simple and easy to understand. Weaknesses: May be slightly less efficient due to loop control overhead.
  • Method 2: Using the hex Method. Strengths: Very straightforward and readable. Weaknesses: Dependence on byte type, not available in older Python versions.
  • Method 3: Using binascii.hexlify. Strengths: Works with large byte arrays efficiently. Weaknesses: Requires an import and additional processing to split the string.
  • Method 4: Using bytes.hex with Slicing. Strengths: No additional imports and it’s efficient for large data processing. Weaknesses: The slicing may be less readable for beginners.
  • Method 5: Using map with format. Strengths: Compact one-liner code. Weaknesses: The use of map and lambda may be less intuitive for newcomers.