2017-08-01 99 views
0

我想寫字節數組(這是Node.js緩衝區)的32位整數。寫32位整數緩衝在Python

據我所知,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

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 

默認表示是帶符號整數的表示。
從文檔:

>>> 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 
+0

您好,感謝您的回答。對不起,如果我誤解了,但在'28 9f 04 03 01 00 00 00 04 00'的Node.js緩衝區上''writeUInt32BE'方法返回'6',但是在Python中'int.from_bytes(b'(\ x9f \ x04 \ x03 \ x01 \ x00 \ x00 \ x00 \ x00 \ x00 \ x04 \ x00',「big」,signed = False)'returns' 191827980698406220727296'參數輸入錯誤?(from_bytes函數的第一個參數是Node.js的緩衝區字符, 。 – ShellRox

+0

@ShellRox你能從上面提出的6的緩衝區表示中驅動任何邏輯嗎? –

+0

因爲丟失了道歉,我使用了'Buffer.allocUnsafe(10).writeUInt32BE(2,2)'來獲得6. – ShellRox