在Python中将32位整数写入缓冲区

时间:2017-08-01 09:12:13

标签: python arrays node.js python-2.7 buffer

我试图将32位整数写入字节数组(即Node.js缓冲区)。

据我所知,Node.js Buffer对象allocUnsafe函数返回以十六进制格式编码的伪随机生成数字的数组。

所以我在Python中解释了Node.js Buffer.allocUnsafe(n)方法:

[c.encode('hex') for c in os.urandom(n)]

但是,allocUnsafe函数有自己的嵌套函数writeInt32BE(value, offset)writeInt32LE(value, offset),我已阅读官方文档,但我不明白从这些函数返回的是什么功能

Python中有这些Node.js函数的等效方法吗?我知道Python中的同等操作可以使用struct模块完成,from_bytes方法也可以,但我不确定如何。提前谢谢。

1 个答案:

答案 0 :(得分:2)

Python提供int.to_bytes(size,byteorder)之类的方法。请参阅here
因此,为了将数字转换为32位,我们将to_bytes方法的长度设为4,即4*8 = 32 bits int.from_bytes函数将字节转换为int请参阅here

 >>> n = 512
 >>> n_byte = (n).to_bytes(4,byteorder='big')
 b'\x00\x00\x02\x00'
 >>> int.from_bytes(n_byte,byteorder='big')
 512

以字节为单位的默认表示是整数的带符号表示 来自docs:

>>> int.from_bytes(b'\x00\x10', byteorder='big')   16  
>>> int.from_bytes(b'\x00\x10', byteorder='little')  4096  
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)  
-1024  
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512  
>>> int.from_bytes([255, 0, 0], byteorder='big')   16711680

您可以查看十六进制表示以转换为整数

>>> hex(6)
'0x6'  
>>> int('0xfeedface',16)
4277009102
相关问题