2024-04-25 04:28:28 发布
网友
字符串中有一长串十六进制数字,例如
000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44
只有更长,几千字节。在Python2.6/3中,是否有内置的方法将其转换为bytes对象?
适用于Python2.7及更高版本,包括python3:
result = bytearray.fromhex('deadbeef')
注意:Python2.6中的bytearray.fromhex()函数似乎有一个bug。org文档指出,函数接受字符串作为参数,但应用时会引发以下错误:
bytearray.fromhex()
>>> bytearray.fromhex('B9 01EF') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: fromhex() argument 1 must be unicode, not str`
你可以用十六进制编解码器来实现。即:
>>> 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'
result = bytes.fromhex(some_hex_string)
适用于Python2.7及更高版本,包括python3:
注意:Python2.6中的
bytearray.fromhex()
函数似乎有一个bug。org文档指出,函数接受字符串作为参数,但应用时会引发以下错误:你可以用十六进制编解码器来实现。即:
相关问题 更多 >
编程相关推荐