"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Convert Hexadecimal Strings to Bytes in Python?

How to Convert Hexadecimal Strings to Bytes in Python?

Published on 2024-12-22
Browse:972

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3