如何从长十六进制字符串创建python字节对象? [英] How to create python bytes object from long hex string?
问题描述
我在字符串中有很长的十六进制数字序列,例如
000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44
blockquote>
只有更长的时间,几千字节。有没有内置的方法可以将它转换为Python 2.6 / 3中的字节对象?
解决方案
python3:
result = bytearray.fromhex('deadbeef')
$ b 注意: > bytearray.fromhex()函数在Python 2.6中。 python.org文档指出该函数接受一个字符串作为参数,但应用时引发以下错误:
>>> bytearray.fromhex('B9 01EF')
Traceback(最近一次调用的最后一次):
在< module>中,第1行的文件< stdin>
TypeError:fromhex()参数1必须是unicode,而不是str
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?
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`
这篇关于如何从长十六进制字符串创建python字节对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!