Home > Article > Backend Development > How to Convert 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.
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.
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.
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!