Signup/Sign In

How To Convert Byte To Hex in Python

In the Python programming language, bytes are like an array. When we want to represent a group of byte values then we can consider bytes() data types. The bytes data types allow values only from 0 to 255. The hex() is one of the built-in functions in python. It converts the specified integer to the corresponding hexadecimal value. It is prefixed with "0x". It returns a hexadecimal string.

In this tutorial, we will learn how to convert bytes to a hexadecimal value using the hex() method and binascii module.

Example: Getting Bytes Object from String

As we all know how to convert any integer or string to a bytes object. Let us start with converting a string to a bytes object. Converted string i.e., bytes object can be used to convert hexadecimal values.

string="March"
print("String to be converted :",string)

byte_data=bytes(string,"utf-16")

print("This is the bytes object.")
print("Converted string is:",byte_data)


String to be converted: March

This is the bytes object.
Converted string is: b'\xff\xfeM\x00a\x00r\x00c\x00h\x00'

Example: Converting bytes to hexadecimal using hex() Method

In the above example, we converted the string to a byte object. We can use that byte object to convert it into a hex value.

byte_data="\xff\xfeM\x00a\x00r\x00c\x00h\x00".encode("utf-16")
print("byte to be converted:",byte_data)
print("byte converted to hexadecimal value:",byte_data.hex())
print("Type of this object is:",type(byte_data.hex()))


byte to be converted: b'\xff\xfe\xff\x00\xfe\x00M\x00\x00\x00a\x00\x00\x00r\x00\x00\x00c\x00\x00\x00h\x00\x00\x00'
byte converted to hexadecimal value: fffeff00fe004d00000061000000720000006300000068000000
Type of this object is: <class 'str'>

Example: Converting bytes to hexadecimal using binascii module.

The binascii module consists of various methods which convert binary to various encoded binary representation. In the binascii module, there is a method called hexlify() which converts the bytes to hexadecimal values.

import binascii
string="studytonight"
print("the string is:", string)
in_bytes=bytes(string,"utf-8")
print("string to byte:",in_bytes)
hex_bytes = binascii.hexlify(in_bytes) 
print("hexlify converts the data to hexdecimal value :",hex_bytes) 
hex_str = hex_bytes.decode("ascii")
print("This is the converted hex value:",hex_str)
# To convert hex to bytes 
y=binascii.unhexlify(hex_str)
# unhexlify converts hex value to bytes.
print(y)


the string is: studytonight
string to byte: b'studytonight'
hexlify converts the data to hexdecimal value : b'7374756479746f6e69676874'
This is the converted hex value: 7374756479746f6e69676874
b'studytonight'

Conclusion

In this tutorial, we learned how to convert bytes object to hex value from the hex() function and binascii module.



About the author:
An enthusiastic fresher, a patient person who loves to work in diverse fields. I am a creative person and always present the work with utmost perfection.