Home >Backend Development >Python Tutorial >How to Convert a Hexadecimal String to Bytes in Python?

How to Convert a Hexadecimal String to Bytes in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-12 04:40:01603browse

How to Convert a Hexadecimal String to Bytes in Python?

How to Convert a Hexadecimal String to Bytes in Python

Converting a hexadecimal string, which represents various data values, to bytes allows you to extract specific values from raw data. Below are various methods to accomplish this in Python.

For instance, converting the string "ab" should result in the bytes b"xab" or its equivalent byte array.

Consider an example where you have a hex string:

8e71c61de6a2321336184f813379ec6bf4a3fb79e63cd12b

How do you convert it to bytes?

Methods:

Bytearray (Python 3 and 2.7):

import binascii

hex_string = "8e71c61de6a2321336184f813379ec6bf4a3fb79e63cd12b"
result = bytearray.fromhex(hex_string)
print(result) # Output: bytearray(b'\x8eq\xc6\x1d\xe6\xa22\x136\x18O\x813y\xeck\xf4\xa3\xfby\xe6<\xd1+')

Bytes Object (Python 3):

bytes_result = bytes.fromhex(hex_string)
print(bytes_result) # Output: b'\x8eq\xc6\x1d\xe6\xa22\x136\x18O\x813y\xeck\xf4\xa3\xfby\xe6<\xd1+'

String (Python ≤ 2.7):

hex_data = hex_string.decode("hex")
print(hex_data) # Output: "\xde\xad\xbe\xef"

The above is the detailed content of How to Convert a Hexadecimal String to Bytes in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn