在python中将整数列表转换为二进制“字符串”

2024-04-28 04:24:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数字列表,我想作为二进制数据发送到套接字连接上。

作为一个例子,我从下面的列表开始:

data = [2,25,0,0,ALPHA,0,23,18,188]

在上面的列表中,ALPHA可以是1到999之间的任意值。最初,我使用

 hexdata = ''.join([chr(item) for item in data])

所以如果ALPHA是101,这将返回以下字符串:

>>> data = [2,25,0,0,101,0,23,18,188]
>>> hexdata = ''.join([chr(item) for item in data])
>>> hexdata
'\x02\x19\x00\x00e\x00\x17\x12\xbc'

这工作得很好,'\x02\x19\x00\x00e\x00\x17\x12\xbc'是我需要发送的字符串。

但是,对于大于255的ALPHA值,这不起作用,因为它超出chr语句的范围。例如,如果ALPHA是999,那么我希望得到以下字符串:

data = [2,25,0,0,999,0,23,18,188]
hexdata = '\x02\x19\x00\x03\xed\x00\x17\x12\xbc'

我一直在查看struct.pack()上的文档,但看不到如何使用它来获取上述字符串。ALPHA是列表中唯一的变量。

任何帮助都将不胜感激。

编辑1

What behavior do you want? Anything between 256 and 65535 takes 2 bytes to represent. Do you want to unpack it on the other side? Please update the post with your intent. – gahooa 1 min ago

这是正确的,因为999超过了256个阈值,它由两个字节表示:

data = [2,25,0,0,999,0,23,18,188]

hexdata = '\x02\x19\x00**\x03\xed**\x00\x17\x12\xbc'

这有道理吗?

就解包而言,im只将这些数据发送到套接字上,我将接收数据,但这已经得到了处理。

编辑2

我发出去的绳子总是固定长度的。 为了简单起见,我认为最好将列表表示如下:

ALPHA = 101

data = [25,alpha1,alpha2,1]
hexdata = '\x19\x00e\x01'


ALPHA = 301

data = [25,alpha1,alpha2,1]
hexdata = 'x19\x01\x2d\x01'

如您在hexdata字符串中所看到的,它将变为:

如果ALPHA<;256,alpha1=0。


Tags: 字符串alpha列表dataitemx17x00x02
3条回答

如果您事先知道数据和ALPHA位置,最好使用struct.pack和该位置的大端号,并省略可能被覆盖的0:

def output(ALPHA):
    data = [2,25,0,ALPHA,0,23,18,188]
    format = ">BBBHBBBB"
    return struct.pack(format, *data)
output(101) # result: '\x02\x19\x00\x00e\x00\x17\x12\xbc'
output(999) # result: '\x02\x19\x00\x03\xe7\x00\x17\x12\xbc'

您可以使用pythonarray

import array
a = array.array('i')
a.extend([2,25,0,0,101,0,23,18,188])
output = a.tostring()

如果ALPHA是<;256,则发送一个字节;如果>;=256,则发送两个字节?这看起来很奇怪——接受者怎么知道是哪种情况。。。???

但是,如果这是你想要的,那么

x = struct.pack(4*'B' + 'HB'[ALPHA<256] + 4*'B', *data)

是实现这一目标的一种方法。

相关问题 更多 >