class method fromHex() of bytes class in Python

The fromHex() method creates a bytes object from a string of hexadecimal digits. Each byte of the input string should correspond two digits of a hexadecimal number.

Bytes Updated 20 Sep 2019 1 min read

Function Name

fromHex

Function Signature

fromHex()

Return Value

bytes

Overview

  • The class method fromHex() creates a bytes object from a string of hexadecimal digits.
  • For the method to work correctly, two hexadecimal digits to be given for every byte in the string. Else it raises a ValueError stating “non-hexadecimal number found in fromhex() arg at position n”

Example

python
# Example Python program to create a bytes literal from

# a string of hexadecimal values

sampleBytes = bytes.fromhex("01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f");

print("bytes object created using fromhex():");

print(sampleBytes);

Output

Output
bytes object created using fromhex():

b'\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'