Convert Bytearray to Hexadecimal String - Python
We are given a byte array a=bytearray([15, 255, 100, 56]) we need to convert it into a hexadecimal string that looks like: 0fff6438.
Python provides multiple ways to do this:
- Using the .hex() method (built-in)
- Using binascii.hexlify()
- Using format() with join()
Let’s explore each method with examples.
Using hex() Method
Python’s bytearray and bytes objects come with a .hex() method that returns a lowercase hexadecimal string for the bytes, without any prefix or separator.
a = bytearray([15, 255, 100, 56])
h = a.hex()
print(h)
Output
0fff6438
Explanation:
- .hex() method automatically converts each byte to a two-digit hexadecimal value.
- All the hex values are joined into one continuous string, no separators, no prefix.
Using binascii.hexlify()
binascii.hexlify() function converts bytes or bytearray into their hexadecimal representation, but returns the result as a bytes object, which you can decode to get a string.
import binascii
a = bytearray([15, 255, 100, 56])
b = binascii.hexlify(a).decode()
print(b)
Output
0fff6438
Explanation:
- binascii.hexlify(a) gives b'0fff6438'.
- .decode() turns the bytes into a normal string.
Note: This method is helpful when working with low-level data formats (e.g., networking or cryptography).
Using format() and join()
We can loop through each byte, format it to a two-character hex using format(byte, '02x'), and then combine the results using ''.join().
a = bytearray([15, 255, 100, 56])
h = ''.join(format(byte, '02x') for byte in a)
print(h)
Output
0fff6438
Explanation:
- format(byte, '02x') ensures each byte is converted to a two-digit hexadecimal string (padded with zero if needed).
- join() merges them into one continuous string.