I have a long sequence of hex digits in a string, such as
000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44
only much longer, several kilobytes. Is there a builtin way to convert this to a bytes object in python 2.6/3?
To convert hex string to byte array, you need to first get the length of the given string and include it while creating a new byte array. byte[] val = new byte[str. length() / 2]; Now, take a for loop until the length of the byte array.
The bytes() function returns a bytes object. It can convert objects into bytes objects, or create empty bytes object of the specified size. The difference between bytes() and bytearray() is that bytes() returns an object that cannot be modified, and bytearray() returns an object that can be modified.
Use the hex() Method to Convert a Byte to Hex in Python The hex() method introduced from Python 3.5 converts it into a hexadecimal string. In this case, the argument will be of a byte data type to be converted into hex.
Works in Python 2.7 and higher including python3:
result = bytearray.fromhex('deadbeef')
Note: There seems to be a bug with the bytearray.fromhex()
function in Python 2.6. The python.org documentation states that the function accepts a string as an argument, but when applied, the following error is thrown:
>>> bytearray.fromhex('B9 01EF') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: fromhex() argument 1 must be unicode, not str`
result = bytes.fromhex(some_hex_string)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With