Home  >  Article  >  Backend Development  >  How to Convert Hexadecimal Strings to Bytes in Python?

How to Convert Hexadecimal Strings to Bytes in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-11 22:40:02404browse

How to Convert Hexadecimal Strings to Bytes in Python?

Converting Hexadecimal Strings to Bytes in Python

In Python, converting hexadecimal strings to bytes is a common task. Hex strings represent binary data in a human-readable format. This article will explore various methods to achieve this conversion effectively.

Method 1: Using bytearray.fromhex() (Recommended for Python 3 and 2.7)

bytearray.fromhex() directly converts a hexadecimal string into a bytearray object. The bytearray acts like a mutable array of bytes.

hex_string = "deadbeef"
bytearray_object = bytearray.fromhex(hex_string)

This method provides a convenient solution for Python 2.7 and Python 3.

Method 2: Using bytes.fromhex() (Python 3 Only)

Similar to bytearray.fromhex(), Python 3 offers bytes.fromhex() to create a bytes object directly from a hex string. The bytes object is immutable and represents a sequence of immutable bytes.

hex_string = "deadbeef"
bytes_object = bytes.fromhex(hex_string)

This method is recommended for Python 3 as it returns a more suitable type.

Method 3: Using String Decoding (Python 2.7 Only)

In Python 2.7, you can decode a hexadecimal string into a string using the decode() method with the "hex" argument.

hex_string = "deadbeef"
string_data = hex_string.decode("hex")

While this method does not create a bytearray or bytes object, it provides a workaround for older versions of Python.

The above is the detailed content of How to Convert Hexadecimal Strings 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