Python | Convert Bytearray to Hexadecimal String - GeeksforGeeks (2024)

Last Updated : 31 Mar, 2023

Summarize

Comments

Improve

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.

Using format() + join() to Convert Byte Array to Hex String

The combination of the above functions can be used to perform this particular task. The format function converts the bytes into hexadecimal format. “02” in format is used to pad required leading zeroes. The join function allows joining the hexadecimal result into a string.

Python3

# 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))

Output:

The original string is : [124, 67, 45, 11]The string after conversion : 7c432d0b

Using binascii.hexlify() to convert Byte Array to Hex String

The inbuilt function of hexlify can be used to perform this particular task. This function is recommended for this particular conversion as it is tailor-made to solve this specific problem.

Python3

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))

Output:

The original string is : [124, 67, 45, 11]The string after conversion : 7c432d0b

Using the bytes.hex() method to directly convert the bytearray to a hexadecimal string:

Step by step Algorithm:

  1. Define a test_list,bytearray containing the bytes to be converted.
  2. Use the hex() method of the bytearray class to convert the bytearray to a hexadecimal string.
  3. Store the resulting hexadecimal string in a variable.
  4. Print the resulting string.

Python3

# define the original bytearray

test_list = [124, 67, 45, 11]

byte_array = bytearray(test_list)

print("The string before conversion: " + str(test_list))

# convert bytearray to hexadecimal string

hex_string = byte_array.hex()

# print the result

print("The string after conversion: " + hex_string)

Complexity Analysis:

Time Complexity: O(n), where n is the length of the input bytearray. The hex() method simply iterates over the bytes in the bytearray and converts each byte to its hexadecimal representation, which takes constant time per byte.

Space Complexity: O(n), since we are creating a new string object to store the resulting hexadecimal string.

RECOMMENDED ARTICLES – Python | bytearray() function

Using the struct module and the h format specifier:

  • 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



manjeet_04

Python | Convert Bytearray to Hexadecimal String - GeeksforGeeks (2)

Improve

Next Article

Python Program to Convert Binary to Hexadecimal

Please Login to comment...

Python | Convert Bytearray to Hexadecimal String - GeeksforGeeks (2024)
Top Articles
Best Online Stock Brokers in the UK
24 Crypto Update, 20 Dec: Crypto Market on the Rise
Kem Minnick Playboy
Fat Hog Prices Today
Terrorist Usually Avoid Tourist Locations
Mrh Forum
How Much Is 10000 Nickels
How Far Is Chattanooga From Here
Wal-Mart 140 Supercenter Products
Mlifeinsider Okta
Locate Td Bank Near Me
Walgreens On Nacogdoches And O'connor
Jc Post News
A rough Sunday for some of the NFL's best teams in 2023 led to the three biggest upsets: Analysis - NFL
Sony E 18-200mm F3.5-6.3 OSS LE Review
iOS 18 Hadir, Tapi Mana Fitur AI Apple?
Tygodnik Polityka - Polityka.pl
Tyler Sis University City
Forest Biome
Form F-1 - Registration statement for certain foreign private issuers
Galaxy Fold 4 im Test: Kauftipp trotz Nachfolger?
MyCase Pricing | Start Your 10-Day Free Trial Today
How to Watch Every NFL Football Game on a Streaming Service
Piedmont Healthstream Sign In
Wonder Film Wiki
Carroway Funeral Home Obituaries Lufkin
By.association.only - Watsonville - Book Online - Prices, Reviews, Photos
Federal Express Drop Off Center Near Me
lol Did he score on me ?
Tu Housing Portal
Warren County Skyward
Exploring TrippleThePotatoes: A Popular Game - Unblocked Hub
Powerball lottery winning numbers for Saturday, September 7. $112 million jackpot
Breckie Hill Fapello
Umiami Sorority Rankings
Ticketmaster Lion King Chicago
450 Miles Away From Me
Compare Plans and Pricing - MEGA
Encompass.myisolved
20 bank M&A deals with the largest target asset volume in 2023
Newsweek Wordle
Jetblue 1919
Nina Flowers
Ehome America Coupon Code
John M. Oakey & Son Funeral Home And Crematory Obituaries
2013 Honda Odyssey Serpentine Belt Diagram
Gas Buddy Il
Best Haircut Shop Near Me
Fluffy Jacket Walmart
Oakley Rae (Social Media Star) – Bio, Net Worth, Career, Age, Height, And More
Houston Primary Care Byron Ga
Renfield Showtimes Near Regal The Loop & Rpx
Latest Posts
Article information

Author: Tish Haag

Last Updated:

Views: 6256

Rating: 4.7 / 5 (47 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Tish Haag

Birthday: 1999-11-18

Address: 30256 Tara Expressway, Kutchburgh, VT 92892-0078

Phone: +4215847628708

Job: Internal Consulting Engineer

Hobby: Roller skating, Roller skating, Kayaking, Flying, Graffiti, Ghost hunting, scrapbook

Introduction: My name is Tish Haag, I am a excited, delightful, curious, beautiful, agreeable, enchanting, fancy person who loves writing and wants to share my knowledge and understanding with you.