Categories
Python Answers

How to convert a hexadecimal string to byte array in Python?

Spread the love

Sometimes, we want to convert a hexadecimal string to byte array in Python.

In this article, we’ll look at how to convert a hexadecimal string to byte array in Python.

How to convert a hexadecimal string to byte array in Python?

To convert a hexadecimal string to byte array in Python, we can use the bytes.fromhex method.

For instance, we write:

hex_string = "deadbeef"
s = bytes.fromhex(hex_string)
print(s)

We define the hex_string hex string.

Then we call bytes.fromhex with it as the argument and assign the returned byte array to s.

Therefore, s is b'\xde\xad\xbe\xef'.

Conclusion

To convert a hexadecimal string to byte array in Python, we can use the bytes.fromhex method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *