如何从长十六进制字符串创建python字节对象?

时间:2021-03-05 15:46:36

I have a long sequence of hex digits in a string, such as

我在字符串中有一长串十六进制数字,例如

000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44

000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44

only much longer, several kilobytes. Is there a builtin way to convert this to a bytes object in python 2.6/3?

只有更长,几千字节。有没有内置的方法将其转换为python 2.6 / 3中的字节对象?

5 个解决方案

#1


41  

Works in Python 2.7 and higher including python3:

适用于Python 2.7及更高版本,包括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:

注意:Python 2.6中的bytearray.fromhex()函数似乎存在错误。 python.org文档声明该函数接受一个字符串作为参数,但是在应用时,会抛出以下错误:

>>> bytearray.fromhex('B9 01EF')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: fromhex() argument 1 must be unicode, not str`

#2


39  

You can do this with the hex codec. ie:

您可以使用十六进制编解码器执行此操作。即:

>>> s='000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44'
>>> s.decode('hex')
'\x00\x00\x00\x00\x00\x00HB@\xfa\x06=\xe5\xd0\xb7D\xad\xbe\xd6:\x81\xfa\xea9\x00\x00\xc8B\x86@\xa4=P\x05\xbdD'

#3


38  

result = bytes.fromhex(some_hex_string)

#4


30  

Try the binascii module

试试binascii模块

from binascii import unhexlify
b = unhexlify(myhexstr)

#5


-2  

import binascii

binascii.b2a_hex(obj)

#1


41  

Works in Python 2.7 and higher including python3:

适用于Python 2.7及更高版本,包括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:

注意:Python 2.6中的bytearray.fromhex()函数似乎存在错误。 python.org文档声明该函数接受一个字符串作为参数,但是在应用时,会抛出以下错误:

>>> bytearray.fromhex('B9 01EF')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: fromhex() argument 1 must be unicode, not str`

#2


39  

You can do this with the hex codec. ie:

您可以使用十六进制编解码器执行此操作。即:

>>> s='000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44'
>>> s.decode('hex')
'\x00\x00\x00\x00\x00\x00HB@\xfa\x06=\xe5\xd0\xb7D\xad\xbe\xd6:\x81\xfa\xea9\x00\x00\xc8B\x86@\xa4=P\x05\xbdD'

#3


38  

result = bytes.fromhex(some_hex_string)

#4


30  

Try the binascii module

试试binascii模块

from binascii import unhexlify
b = unhexlify(myhexstr)

#5


-2  

import binascii

binascii.b2a_hex(obj)