Python | Convert Bytearray to Hexadecimal String
Sometimes, we might be in a problem in which we need to handle the unusual datatype conversions. One such conversion can be converting the list of bytes(bytearray) to the Hexadecimal string format. Let’s discuss certain ways in which this can be done.
Method #1 : Using format() + join()
The combination of above functions can be used to perform this particular task. The format function converts the bytes in hexadecimal format. “02” in format is used to pad required leading zeroes. The join function allows to join the hexadecimal result into a string.
# Python3 code to demonstrate working of # Converting bytearray to hexadecimal string # Using join() + format() # initializing list test_list = [124, 67, 45, 11] # printing original list print("The original string is : " + str(test_list)) # using join() + format() # Converting bytearray to hexadecimal string res = ''.join(format(x, '02x') for x in test_list) # printing result print("The string after conversion : " + str(res)) |
The original string is : [124, 67, 45, 11] The string after conversion : 7c432d0b
Method #2 : Using binascii.hexlify()
The inbuilt function of hexlify can be used to perform this particular task. This function is recommended for this particular conversion as it is tailormade to solve this specific problem.
# Python3 code to demonstrate working of # Converting bytearray to hexadecimal string # Using binascii.hexlify() import binascii # initializing list test_list = [124, 67, 45, 11] # printing original list print("The original string is : " + str(test_list)) # using binascii.hexlify() # Converting bytearray to hexadecimal string res = binascii.hexlify(bytearray(test_list)) # printing result print("The string after conversion : " + str(res)) |
The original string is : [124, 67, 45, 11] The string after conversion : 7c432d0b
Recommended Posts:
- Python | bytearray() function
- Python | Convert None to empty string
- Python | Convert String to bytes
- Python | Convert String to Binary
- Python | Program to convert String to a List
- Python | Convert dictionary object into string
- Python | Convert a list of characters into a string
- Python program to convert a list to string
- Python | Program to convert a tuple to a string
- Python program to convert hex string to decimal
- Python | Ways to convert list of ASCII value to string
- Python | Convert byteString key:value pair of dictionary to String
- Python | Ways to convert string to json object
- Python | Convert string to DateTime and vice-versa
- Python | Convert tuple records to single string
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



