How to use the struct module and the h format specifier In Python
- Import the struct module
- Define the original bytearray
- Convert each byte in the bytearray to a binary string using the struct.pack() function and the B format specifier
- Convert each binary string to a hexadecimal string using the hex() method
- Concatenate the hexadecimal strings for each byte into a single string using the join() method
- Print the original bytearray and the resulting hexadecimal string
Python3
import struct # Define the original bytearray test_list = [ 124 , 67 , 45 , 11 ] byte_array = bytearray(test_list) # Convert bytearray to hexadecimal string using the struct module hex_string = ' '.join(struct.pack(' B', x). hex () for x in byte_array) # Print the result print ( "The string before conversion: " + str (test_list)) print ( "The string after conversion: " + hex_string) |
Output
The string before conversion: [124, 67, 45, 11] The string after conversion: 7c432d0b
Time complexity: O(n), where n is the length of the byte array
Auxiliary Space: O(n), since we are creating a new string to hold the concatenated hexadecimal strings
Using codecs.encode()
- Import the codecs module.
- Define a list of integers that represent the original bytearray.
- Create a bytearray from the list of integers.
- Use the codecs.encode() method to convert the bytearray to a hexadecimal string, then decode it to a regular string.
- Print the original list of integers and the converted hexadecimal string.
Python3
import codecs #Define the original bytearray test_list = [ 124 , 67 , 45 , 11 ] byte_array = bytearray(test_list) #Convert bytearray to hexadecimal string using codecs.encode() hex_string = codecs.encode(byte_array, 'hex' ).decode() #Print the result print ( "The string before conversion: " + str (test_list)) print ( "The string after conversion: " + hex_string) |
Output
The string before conversion: [124, 67, 45, 11] The string after conversion: 7c432d0b
The time complexity of this code is O(n), where n is the length of the input list.
The auxiliary space of this code is also O(n), as it creates a new bytearray and a new string
Python | Convert Bytearray to Hexadecimal String
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.