bytes.hex() Method - Python
Last Updated :
10 Mar, 2025
Improve
bytes.hex() method returns a string representing the hexadecimal encoding of a bytes object. Each byte is represented by two hexadecimal digits making it useful for displaying binary data in a readable form. For Example:
# byte_data
d = b'Hello World'
# hex string
s = d.hex()
print(s)
Output
48656c6c6f20576f726c64
Explanation:
- bytes.hex() method converts the bytes object b'Hello World' into a hexadecimal string.
- each byte in the original data is represented by two hexadecimal characters.
- output "48656c6c6f20576f726c64" is the hex representation of "Hello World".
Table of Content
Syntax of bytes.hex()
bytes.hex()
Parameters : No parameters.
Return Type: returns a string containing the hexadecimal representation of the bytes object.
Converting Bytes to Hexadecimal String
bytes.hex() method is commonly used to convert binary data into a human-readable hexadecimal format.
# binary_data
d = b'Network'
# hex_representation
s = d.hex()
print(s)
Output
4e6574776f726b
Explanation:
- bytes.hex() method converts the bytes object b'Network' into a hexadecimal string.
- each character in "Network" is encoded into its corresponding hexadecimal representation.
- output "4e6574776f726b" represents "Network" in hexadecimal format.
Displaying Encrypted Data in Hex
This method is useful when displaying encrypted data, allowing it to be easily read or transmitted in a hexadecimal format.
# cipher
c = b'SecretKey'
# hex_cipher
hc = c.hex()
print(hc)
Output
5365637265744b6579
Explanation:
- bytes.hex() method converts the bytes object b'SecretKey' into a hexadecimal string.
- each character in "SecretKey" is encoded into its corresponding hexadecimal value.
- output "5365637265744b6579" represents "SecretKey" in hexadecimal format.