如何将整数列表转换为单个字节的字符串?

问题描述 投票:0回答:1

我正在尝试以十六进制(或十进制,对于我认为的问题而言并没有真正产生影响)将字节列表打印到文件中。我很困惑这在 Python 中看起来有多难?

根据我发现的here(以及其他SO问题),我已经设法做到了这一点:

>>> b
[12345, 6789, 7643, 1, 2]
>>> ' '.join(format(v, '02x') for v in b)
'3039 1a85 1ddb 01 02'

现在...这已经是一个好的开始,但是...对于更大的数字,各个字节被分组并相互连接。这不应该发生。它们之间应该有一个空格,就像最后两个数字的情况一样。

当然,我可以在之后进行一些字符串操作并插入一些空格,但是......这听起来像是一种非常老套的方式,而且我拒绝相信没有更干净的方法来做到这一点。

所以,我想要的是这样的:

'30 39 1a 85 1d db 01 02'

我该怎么做?

python python-3.x string list hex
1个回答
0
投票

好的,所以这有点拼凑在一起,但应该做你想做的:

from textwrap import wrap

int_list = [12345, 6789, 7643, 1, 2]  # here's your list of ints

# convert all the values to hex, and then join them together as a string,
# using slicing ([2:]) to strip off the '0x' hexadecimal prefix from each
# (zfill is used to pad smaller values with zeros as needed, e.g. 01 and 02)
byte_string = ''.join([hex(n)[2:].zfill(2) for n in int_list])
# => '30391a851ddb0102'

# use the 'wrap' method from the textwrap module to group the bytes into
# groups of 2, then 'join' the resulting list with spaces in between
new_bytes = ' '.join(wrap((byte_string), 2))
# => '30 39 1a 85 1d db 01 02'
© www.soinside.com 2019 - 2024. All rights reserved.