【问题标题】:splitting a string into a list of 2char strings将字符串拆分为 2char 字符串列表
【发布时间】:2011-11-13 20:12:01
【问题描述】:

我有一个十六进制流,例如:1a2b3c4d5e6f7g 但更长 我想将其拆分为列表中的 2char 十六进制值,然后将它们转换为 ascii。

【问题讨论】:

标签: python hex ascii


【解决方案1】:

binascii.unhexlify(hexstr) 呢?
请参阅 binascii 模块的文档:http://docs.python.org/library/binascii.html

【讨论】:

  • +1 binascii.unhexlify('7573652062696e61736369692e756e6865786c696679') 给'use binascii.unhexlify'
【解决方案2】:

在 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'

【讨论】:

  • 它好像还有另一个名字:a2b_hex >>>binascii.a2b_hex('abcdef0123456789') Out[0]: '\xab\xcd\xef\x01#Eg\x89'
【解决方案3】:

一个班轮:

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

【讨论】:

    猜你喜欢
    • 2019-04-16
    • 2015-09-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多