簡體   English   中英

將struct.unpack從python 2.7移植到3

[英]Porting struct.unpack from python 2.7 to 3

以下代碼在python 2.7中工作正常:

def GetMaxNoise(data, max_noise):
    for byte in data:
        noise = ComputeNoise(struct.unpack('=B',byte)[0])
        if max_noise < noise:
            max_noise = noise
    return max_noise

其中data是包含二進制數據的字符串(取自網絡數據包)。

我正在嘗試將其移植到Python 3,我得到了這個:

在GetMaxNoise中的文件“Desktop / Test.py”,第2374行

noise = ComputeNoise(struct.unpack('= B',byte)[0])

TypeError:'int'不支持緩沖區接口

如何將“數據”轉換為unpack()所需的適當類型?

假設data變量是從網絡數據包上的二進制文件獲得的字節字符串 ,它在Python2和Python3中的處理方式不同。

在Python2中,它是一個字符串。 當你迭代它的值時,你得到單字節字符串,你用struct.unpack('=B')[0]轉換為int

在Python3中,它是一個bytes對象。 當你迭代它的值時,你直接獲得整數! 所以你應該直接使用:

def GetMaxNoise(data, max_noise):
    for byte in data:
        noise = ComputeNoise(byte)  # byte is already the int value of the byte...
        if max_noise < noise:
            max_noise = noise
    return max_noise

從結構模塊https://docs.python.org/3.4/library/struct.html的文檔中我看到unpack方法期望它是實現緩沖協議的第二個參數,因此它通常需要bytes

您的data對象似乎是從某處讀取的bytes類型。 當您使用for循環迭代它時,您最終將byte變量作為單個int值。

我不知道你的代碼應該做什么以及如何做,但是可能會改變迭代你的data對象以處理不是int的方式但是length == 1 bytes

for i in range(len(data)):
    byte = data[i:i+1]
    print(byte)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM