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.
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