How to create python bytes object from long hex string?
Question:
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?
Answers:
Try the binascii module
from binascii import unhexlify
b = unhexlify(myhexstr)
You can do this with the hex codec. ie:
>>> s='000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44'
>>> s.decode('hex')
'x00x00x00x00x00x00HB@xfax06=xe5xd0xb7Dxadxbexd6:x81xfaxea9x00x00xc8Bx86@xa4=Px05xbdD'
result = bytes.fromhex(some_hex_string)
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`
import binascii
binascii.a2b_hex(hex_string)
Thats the way I did it.
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?
Try the binascii module
from binascii import unhexlify
b = unhexlify(myhexstr)
You can do this with the hex codec. ie:
>>> s='000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44'
>>> s.decode('hex')
'x00x00x00x00x00x00HB@xfax06=xe5xd0xb7Dxadxbexd6:x81xfaxea9x00x00xc8Bx86@xa4=Px05xbdD'
result = bytes.fromhex(some_hex_string)
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`
import binascii
binascii.a2b_hex(hex_string)
Thats the way I did it.