bytes.fromhex() Method - Python
bytes.fromhex() method converts a hexadecimal string into a bytes object. Each pair of hex digits represents one byte making it useful for decoding hexadecimal-encoded data. For Example:
hex_str = "48656c6c6f20576f726c64" # Hex representation of "Hello World"
byte_data = bytes.fromhex(hex_str)
print(byte_data)
Output
b'Hello World'
Syntax of bytes.fromhex()
bytes.fromhex(string)
- Parameters: string: A hexadecimal string containing only valid hex characters (0-9, A-F).
- Return: Returns a bytes object containing the decoded binary data.
Converting Hexadecimal Strings to Bytes
When working with hexadecimal-encoded data, bytes.fromhex() helps in decoding it back into a bytes object.
hex_code = "4e6574776f726b"
res = bytes.fromhex(hex_code)
print(res)
Output
b'Network'
Explanation:
- hexadecimal string "4e6574776f726b" corresponds to the word "Network".
- bytes.fromhex(hex_code) decodes the hex string into the bytes object: b'Network'.
Processing Encrypted Data
This method is often used in cryptography or network communication when dealing with encoded binary data.
# cipher_text
s = "5365637265744b6579"
# decoded_cipher
o = bytes.fromhex(s)
print(o)
Output
b'SecretKey'
Explanation:
- hexadecimal string "5365637265744b6579" represents the ASCII encoding of "SecretKey".
- bytes.fromhex(s) converts this hex string into the bytes object: b'SecretKey'.
- output of print(o) is b'SecretKey', showing the decoded string as bytes.