w3resource

Python: Convert a given Bytearray to Hexadecimal string

Python String: Exercise-85 with Solution

Write a Python program to convert a given Bytearray to a Hexadecimal string.

Sample Solution:-

Python Code:

# Define a function to convert a bytearray to a hexadecimal string
def bytearray_to_hexadecimal(list_val):
    # Use a generator expression to convert each byte in the list to a two-digit hexadecimal representation
    result = ''.join('{:02x}'.format(x) for x in list_val)
    	
    # Return the resulting hexadecimal string
    return result

# Create a bytearray represented by a list of integers
list_val = [111, 12, 45, 67, 109]

# Print the original list representing the bytearray
print("Original Bytearray :")
print(list_val)

# Print a newline for better formatting
print("\nHexadecimal string:")

# Call the function to convert the bytearray to a hexadecimal string and print the result
print(bytearray_to_hexadecimal(list_val)) 

Sample Output:

Original Bytearray :
[111, 12, 45, 67, 109]

Hexadecimal string:
6f0c2d436d

Flowchart:

Flowchart: Convert a given Bytearray to Hexadecimal string.

Python Code Editor:

Previous: Write a Python program to swap cases of a given string.
Next: Write a Python program to delete all occurrences of a specified character in a given string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.