如何将7e0acdbf6a527e转换为0x7e 0x0a 0xcd 0xbf格式并在python中存储在数组中

如何将7e0acdbf6a527e转换为0x7e 0x0a 0xcd 0xbf格式并在python中存储在数组中,python,Python,我正在尝试用python将7e0acdbf6a527e转换为0x7e 0x0a 0xcd 0xbf,有人能帮我吗?您可以使用来获取字符对: from itertools import izip_longest # or zip_longest in Python 3.x def grouper(iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper('AB

我正在尝试用python将7e0acdbf6a527e转换为0x7e 0x0a 0xcd 0xbf,有人能帮我吗?

您可以使用来获取字符对:

from itertools import izip_longest # or zip_longest in Python 3.x

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args) # see comment above
然后:

这给了我:

>>> s="7e0acdbf6a527e"
>>> hexes = ["0x{0}".format("".join(t)) for t in grouper(s, 2)]
>>> hexes
['0x7e', '0x0a', '0xcd', '0xbf', '0x6a', '0x52', '0x7e']
您还可以通过以下方式:

>>> [int(s, 16) for s in hexes]
[126, 10, 205, 191, 106, 82, 126]

如果数据是字符串,则可以执行以下操作:

data = "7e0acdbf6a527e"
mod = zip(data[::2], data[1::2])
result = ['0x{}'.format(''.join(item)) for item in mod]
['0x7e', '0x0a', '0xcd', '0xbf', '0x6a', '0x52', '0x7e']

这完全取决于你真正想要什么

要将它们作为实际整数处理,请执行以下操作:

>>> s = "7e0acdbf6a527e"
>>> result = ['0x' + s[i:i+2] for i in range(0, len(s), 2)]
>>> print [int(x, 16) for x in result]
[126, 10, 205, 191, 106, 82, 126]

从十六进制字符串到数字序列还有两个简单的变体:

>>> string = '7e0acdbf6a527e'
>>> import binascii, array
>>> a=array.array('B', binascii.a2b_hex(string))
>>> a
array('B', [126, 10, 205, 191, 106, 82, 126])
>>> map(hex,a)
['0x7e', '0xa', '0xcd', '0xbf', '0x6a', '0x52', '0x7e']
>>> a=[int(string[i:i+2], 16) for i in range(0,len(string),2)]
>>> a
[126, 10, 205, 191, 106, 82, 126]

但问题是缺少上下文(例如您正在尝试做什么,或者这些值具有或应该具有什么数据类型)

你说的是十六进制字符串还是实际的字节序列?
>>> s = "7e0acdbf6a527e"
>>> result = ['0x' + s[i:i+2] for i in range(0, len(s), 2)]
>>> print [int(x, 16) for x in result]
[126, 10, 205, 191, 106, 82, 126]
string = '7e0acdbf6a527e'

answer = ['0x{0}'.format(string[ii-1:ii+1]) for ii in xrange(1,len(string)+1,2)]
>>> string = '7e0acdbf6a527e'
>>> import binascii, array
>>> a=array.array('B', binascii.a2b_hex(string))
>>> a
array('B', [126, 10, 205, 191, 106, 82, 126])
>>> map(hex,a)
['0x7e', '0xa', '0xcd', '0xbf', '0x6a', '0x52', '0x7e']
>>> a=[int(string[i:i+2], 16) for i in range(0,len(string),2)]
>>> a
[126, 10, 205, 191, 106, 82, 126]