Free cookie consent management tool by TermsFeed The fromhex() method of bytearray class in Python | Pythontic.com

The fromhex() method of bytearray class in Python

Overview:

  • The fromhex() method converts hexadecimal digits from a string, bytes or from a bytes-like object into a bytearray.
  • The method accepts even number of hexadecimal digits and returns a bytearray object. The input cannot be odd number of digits as the resultant bytearray can have only “n” number of bytes. It cannot have fractions of a byte, like a half byte. When odd number of digits are passed as the input, the method fromhex() will raise an exception stating “ValueError: fromhex() arg must contain an even number of hexadecimal digits”.
  • The input parameter cannot contain any non-hexadecimal number. For example, the string “ABC%” cannot be converted using fromhex() as the input string has non-hexadecimal digits.

Hexa decimal number represented by bits

Note:

1 bit represents up to 2 values – 0 and 1.

2 bits represent up to 4 values – 00, 01, 10, 11.

4 bits represent up to 16 values - 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111, 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111.  One hexadecimal digit can be represented using 4 bits. A byte can represent two hexadecimal digits.

Example 1 - Create a bytearray from a string of hexadecimal digits:

# Example Python program that converts the 
# hexadecimal digits from a string to bytearray
asciiString = "08090A"

# Convert to bytearray
hexBytes = bytearray.fromhex(asciiString)

print("The bytearray:")
print(hexBytes)

print("Length of the bytearray:")
print(len(hexBytes))

Output:

The bytearray:
bytearray(b'\x08\t\n')
Length of the bytearray:
3

Example 2 - Create a bytearray from a bytes-like object:

# Example Python program that converts the 
# hexadecimal digits from a bytes-like object 
# to a bytearray
memView = memoryview(b"01020e0f")

# Convert to bytearray
byteArrayOb = bytearray.fromhex(memView)

print("The bytearray object:")
print(byteArrayOb)

Output:

The bytearray object:
bytearray(b'\x01\x02\x0e\x0f')

 


Copyright 2025 © pythontic.com