Python – Hex String to Bytearray

4.7/5 - (3 votes)

Problem Formulation

Given a string in hexadecimal form:

hex_string = '0f'

How to convert the hex string to a bytearray object in Python?

# Output:

Here are a few examples:

Hex StringBytearray Object
'01 0a'bytearray(b'\x01\n')
'01 02 0e 0f 0f'bytearray(b'\x01\x02\x0e\x0f\x0f')
'0f 0f'bytearray(b'\x0f\x0f')

Hex String to Bytearray using bytearray.fromhex(hex_string)

To convert a hexadecimal string to a bytearray object, pass the string as a first argument into bytearray.fromhex(hex_string) method. For example, bytearray.fromhex('ff') yields bytearray(b'\xff').

Here’s a minimal example:

hex_string = 'ff'
# bytearray(b'\xff')

🌍 Recommended Tutorial: How to Convert Hex String to Integer in Python


And here’s how you can convert the additional examples shown above:

>>> bytearray.fromhex('01')
>>> bytearray.fromhex('0101')
>>> bytearray.fromhex('04')
>>> bytearray.fromhex('01 0a')
>>> bytearray.fromhex('01 02 0e 0f 0f')
>>> bytearray.fromhex('0f0f')
>>> bytearray.fromhex('ff')

Convert Hex String with Prefix ‘0x’ to Bytearray

If your hex string has a prefix '0x' in front of it, you can convert it into a bytearray object by using slicing operation hex_string[2:] to get rid of the prefix before converting it using bytearray.fromhex(hex_string[2:]).

hex_string = '0x0f'
# bytearray(b'\x0f')

If you don’t know slicing well enough in Python, feel free to check out my in-depth tutorial here:

The Ultimate Guide to Slicing in Python

🌍 Recommended Tutorial: Python Slicing Ultimate Guide

[Fix] Value Error Non-Hexadecimal Number in fromhex()

Note that if you don’t get rid of the string hex prefix '0x', you run in the ValueError: non-hexadecimal number found in fromhex() arg at position 1.

>>> bytearray.fromhex('0xff')
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
ValueError: non-hexadecimal number found in fromhex() arg at position 1

You can fix this ValueError: non-hexadecimal number found in fromhex() arg at position 1 by getting rid of the '0x' prefix using slicing hex_string[2:] before passing it into the fromhex() method.

Convert Hex String to Bytes

A simple way to convert a hexadecimal string hex_string to a bytes type is to use the bytes.fromhex(hex_string) method. For example, bytes.fromhex('deadbeef') returns the b'\xde\xad\xbe\xef' type.

Here’s a minimal example:

hex_string = 'deadbeef'
# b'\xde\xad\xbe\xef'

🌍 Recommended Tutorial: How to Convert a Hex String to a Bytes Object in Python?

After reading this, you may wonder:

What’s the Difference Between bytearray and bytes?

The difference between bytearray and bytes types is that bytes is an immutable version of bytearray. So you can modify an object of the latter but not of the former.

For example, let’s create both types from the same hex_string as learned before:

hex_string = 'deadbeef'
my_bytes = bytes.fromhex(hex_string)
my_bytearray = bytearray.fromhex(hex_string)

Next, you’ll change the my_bytearray variable — no problem:

# bytearray(b'\xde\xad\xbe\xef')

# Modify bytearray is possible
my_bytearray[0] = 3

# bytearray(b'\x03\xad\xbe\xef')

But what happens if you try to modify the my_bytes variable? An error TypeError: 'bytes' object does not support item assignment!

>>> my_bytes[0] = 3
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    my_bytes[0] = 3
TypeError: 'bytes' object does not support item assignment

To fix this error, don’t change the bytes type in your code snippet or use a mutable bytearray instead of an immutable bytes type.

🌍 Recommended Tutorial: Mutable vs Immutable Objects in Python

Where to Go From Here

Thanks for reading through the whole tutorial—I’m happy and grateful that you visited us on the Finxter blog because my mission is to help coders like you reach their goals faster.

I believe in the transformative power we coders have to change the world and make it more efficient!

If you want to keep improving your skills, feel free to check out my free email academy and download Python Cheat Sheets here: