我需要在Python中发送一个字节消息,我需要将无符号整数转换为字节数组.如何在Python中将整数值转换为四个字节的数组?就像C:
uint32_t number=100;
array[0]=(number >>24) & 0xff;
array[1]=(number >>16) & 0xff;
array[2]=(number >>8) & 0xff;
array[3]=number & 0xff;
Run Code Online (Sandbox Code Playgroud)
有人能告诉我怎么样?起初我很奇怪没有类型的程序.
Sve*_*ach 32
看看struct模块.您可能只需struct.pack("I", your_int)要将整数打包到字符串中,然后将此字符串放在消息中.格式字符串"I"表示无符号的32位整数.
如果要将这样的字符串解压缩为整数元组,可以使用struct.unpack("4b", s):
>>> struct.unpack("4b", struct.pack("I", 100))
(100, 0, 0, 0)
Run Code Online (Sandbox Code Playgroud)
(示例显然是在小端机器上.)
cha*_*e80 17
这是一个老线程,但在Python 3.2+现在你可以简单地说:
number = 100
number.to_bytes(4, byteorder = 'big')
Run Code Online (Sandbox Code Playgroud)
或byteorder = 'little'根据您的需要.文档在这里.
Obe*_*nne 14
斯文你有答案吗?但是,在Python中也可以使用字节移位数字(如您的问题中所示):
>>> [hex(0x12345678 >> i & 0xff) for i in (24,16,8,0)]
['0x12', '0x34', '0x56', '0x78']
Run Code Online (Sandbox Code Playgroud)
小智 7
如果有人在某个时候看过这个问题......
这个陈述应该等同于原始问题中的代码:
>>> tuple( struct.pack("!I", number) )
('\x00', '\x00', '\x00', 'd')
Run Code Online (Sandbox Code Playgroud)
而且我认为主机字节顺序不重要.
如果整数大于int32,则可以"!Q"在pack()对int64 的调用中使用(如果系统支持Q).
而且list()甚至bytearray()会代替tuple().
注意,结果是一系列str对象(每个对象持有一个字节),而不是整数.如果必须有整数列表,则可以执行以下操作:
[ ord(c) for c in struct.pack("!I", number) ]
[0, 0, 0, 100]
Run Code Online (Sandbox Code Playgroud)
... 或这个:
>>> map( ord, tuple( struct.pack("!I", number) ) )
[0, 0, 0, 100]
Run Code Online (Sandbox Code Playgroud)
但使用map()开始使事情有点混乱.
你几乎可以做同样的事情:
>>> number = 100
>>> array[0] = (number>>24) & 0xff
>>> array[1] = (number>>16) & 0xff
>>> array[2] = (number>>8) & 0xff
>>> array[3] = number & 0xff
Run Code Online (Sandbox Code Playgroud)
或者你可以做一些更短的事情:
>>> array = [(number>>(8*i))&0xff for i in range(3,-1,-1)]
Run Code Online (Sandbox Code Playgroud)