How to Convert Hexadecimal Strings to Bytes in Python?

Mary-Kate Olsen
Release: 2024-11-11 22:40:02
Original
404 people have browsed it

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)
Copy after login

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)
Copy after login

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")
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template