2016-02-21 68 views
3

使用Python 2.7的字符串參數我有這樣的代碼:錯誤解壓需要長度16

#Create a random 56 bit (7 byte) string 
random_bytes = os.urandom(7) 
random_bytes = int.from_bytes(random_bytes, byteorder="big") 

這給錯誤:

AttributeError: type object 'int' has no attribute 'from_bytes'

在線閱讀,它看起來像from_bytes是Python 3中之後。所以我嘗試了以下內容:

random_bytes = os.urandom(7) 
    #random_bytes = int.from_bytes(random_bytes, byteorder="big") 
    random_bytes = struct.unpack('>16B', random_bytes) 

但是,這給出了以下錯誤:

struct.error: unpack requires a string argument of length 16

>16B應該是>7B?即使這樣,它似乎返回一個元組。

的目標是使用random_bytes像這樣:

int(str(((time_bytes << 56) | random_bytes)) + code) 
+0

http://stackoverflow.com/questions/30402743/python-2-7-equivalent-of-built-in-method-int-from-bytes這是否有幫助? – timgeb

+0

@timgeb不,我確定''struct.unpack''是去這裏的方式 – Prometheus

+1

你問結構將7字節的序列解壓縮成一個16位,8位整數的元組... – thebjorn

回答

1

也許這會爲你工作:

r = chr(0) + os.urandom(7) # pad with zeroes 
struct.unpack('>q', r) 

q是用於簽名的8字節inte的代碼ger(Q未簽名)。

結果是一個元素的元組。

2

也許這將幫助:

import os 

binary = os.urandom(7) 
result = int(binary.encode('hex'), 16) 
相關問題