bytes.fromhex() is a built-in class method that converts a hexadecimal string into a bytes object. Every two hexadecimal characters represent one byte. This method is commonly used when working with hexadecimal-encoded data and binary information.
h = "48656c6c6f"
b = bytes.fromhex(h)
print(b)
Output
b'Hello'
Explanation: bytes.fromhex(h) converts the hexadecimal string "48656c6c6f" into the bytes object b'Hello'.
Syntax
bytes.fromhex(string)
- Parameter: string - A string containing hexadecimal characters. Each pair of hexadecimal digits is converted into one byte.
- Return: Returns a bytes object containing the decoded binary data.
Examples
Example 1: This example converts a hexadecimal string representing a word into a bytes object.
h = "4e6574776f726b"
b = bytes.fromhex(h)
print(b)
Output
b'Network'
Explanation: bytes.fromhex(h) converts the hexadecimal string "4e6574776f726b" into the bytes object b'Network'
Example 2: This example decodes hexadecimal values that represent a string containing numbers.
h = "3132333435"
b = bytes.fromhex(h)
print(b)
Output
b'12345'
Explanation: bytes.fromhex(h) converts the hexadecimal string "3132333435" into the bytes object b'12345'.
Example 3: In this example, bytes.fromhex() ignores spaces between hexadecimal values, making long hexadecimal strings easier to read.
h = "48 65 6c 6c 6f 20 50 79 74 68 6f 6e"
b = bytes.fromhex(h)
print(b)
Output
b'Hello Python'
Explanation: bytes.fromhex(h) ignores the spaces and converts the hexadecimal values into the bytes object b'Hello Python'.