Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Convert Bytearray to Hexadecimal String using Python?
A hexadecimal string is a textual representation of data using base-16 notation, combining digits 0-9 and letters A-F. Each hexadecimal character represents 4 bits, making it useful for displaying binary data in a compact, human-readable format. Python provides several methods to convert a bytearray to hexadecimal string.
What is a Bytearray?
A bytearray is a mutable sequence of bytes in Python. Unlike strings, bytearrays can be modified after creation and are ideal for handling binary data like images, network packets, or cryptographic operations. Each element is an integer from 0 to 255.
# Creating a bytearray
data = bytearray(b'Hello')
print("Bytearray:", data)
print("Type:", type(data))
Bytearray: bytearray(b'Hello') Type: <class 'bytearray'>
Using the binascii Module
The binascii.hexlify() function is the most straightforward method for converting binary data to hexadecimal ?
import binascii
byte_array = bytearray(b'Hello, World!')
hex_string = binascii.hexlify(byte_array).decode('utf-8')
print("Hexadecimal string:", hex_string)
Hexadecimal string: 48656c6c6f2c20576f726c6421
Using List Comprehension with format()
This approach converts each byte to its two-digit hexadecimal representation using format() ?
byte_array = bytearray(b'Python')
hex_string = ''.join([format(byte, '02x') for byte in byte_array])
print("Hexadecimal string:", hex_string)
Hexadecimal string: 507974686f6e
Using the hex() Function
The hex() function converts each byte individually, requiring removal of the '0x' prefix ?
byte_array = bytearray(b'Data')
hex_string = ''.join(hex(byte)[2:].zfill(2) for byte in byte_array)
print("Hexadecimal string:", hex_string)
Hexadecimal string: 44617461
Using the hex() Method (Python 3.5+)
Python 3.5+ provides a built-in hex() method for bytes and bytearray objects ?
byte_array = bytearray(b'TutorialsPoint')
hex_string = byte_array.hex()
print("Hexadecimal string:", hex_string)
Hexadecimal string: 5475746f7269616c73506f696e74
Comparison
| Method | Performance | Readability | Python Version |
|---|---|---|---|
binascii.hexlify() |
Fast | Good | All versions |
format() + comprehension |
Medium | Excellent | All versions |
hex() function |
Slower | Good | All versions |
.hex() method |
Fastest | Excellent | 3.5+ |
Conclusion
Use the .hex() method for Python 3.5+ as it's the fastest and most readable. For older Python versions, binascii.hexlify() offers good performance and simplicity for converting bytearrays to hexadecimal strings.
