【发布时间】:2011-11-13 20:12:01
【问题描述】:
我有一个十六进制流,例如:1a2b3c4d5e6f7g 但更长 我想将其拆分为列表中的 2char 十六进制值,然后将它们转换为 ascii。
【问题讨论】:
-
包含字符“g”的“十六进制流”确实是一种非常有趣的动物。
我有一个十六进制流,例如:1a2b3c4d5e6f7g 但更长 我想将其拆分为列表中的 2char 十六进制值,然后将它们转换为 ascii。
【问题讨论】:
binascii.unhexlify(hexstr) 呢?
请参阅 binascii 模块的文档:http://docs.python.org/library/binascii.html
【讨论】:
binascii.unhexlify('7573652062696e61736369692e756e6865786c696679') 给'use binascii.unhexlify'
在 Python 2.x 中你可以使用binascii.unhexlify:
>>> import binascii
>>> binascii.unhexlify('abcdef0123456789')
'\xab\xcd\xef\x01#Eg\x89'
在 Python 3 中有一个更优雅的方法,只使用内置的 bytes 类型:
>>> bytes.fromhex('abcdef0123456789')
b'\xab\xcd\xef\x01#Eg\x89'
【讨论】:
一个班轮:
a = "1a2b3c"
print ''.join(chr(int(a[i] + a[i+1], 16)) for i in xrange(0, len(a), 2))
解释:
xrange(0, len(a), 2) # gives alternating indecis over the string
a[i] + a[i+1] # the pair of characters as a string
int(..., 16) # the string interpreted as a hex number
chr(...) # the character corresponding to the given hex number
''.join() # obtain a single string from the sequence of characters
【讨论】: