簡體   English   中英

如何將此 Python2 代碼轉換為 Python3?

[英]How do I convert this Python2 code into Python3?

我在轉換這個 Python 2 代碼時遇到了一些麻煩:

import md5

steamid=76561197960435530
temp = ""
for i in range(8):
    temp +=  chr((steamid & 0xFF))
    steamid >>= 8
m = md5.new("BE"+temp)

print m.hexdigest()

進入 Python 3,上面代碼的結果是 'a071c58205ec529c5c19fa7dadcaae93'。 但是,當我嘗試使用 hashlib 庫在 Python 3 中重現相同的代碼時,我得到了完全不同的返回。 我希望它返回與 Python 2 代碼完全相同的內容。 這是我在 Python 3 中重現代碼的嘗試:

from hashlib import md5

steamid = 76561197960435530
temp = ""
for i in range(8):
    temp +=  chr((steamid & 0xFF))
    steamid >>= 8
m = md5()
m.update(("BE"+temp).encode())

print(m.hexdigest())

它返回 'a96d4d4b56a3b5c1a747e01dd7045c6d' 這不是我希望它返回的。

在 Python 3 中,您正在構建具有正確代碼點的字符串,然后使用encode()將其轉換為字節。 這就是問題所在: encode()將對字符串中的代碼點進行 UTF8 編碼,這將導致字節序列與預期的不同。 為了避免這個問題,你應該從頭開始使用字節:

from hashlib import md5

steamid = 76561197960435530
temp = bytearray()
for i in range(8):
    temp.append(steamid & 0xFF)
    steamid >>= 8
m = md5()
m.update((b"BE" + temp))

print(m.hexdigest())

作為一個額外的好處,這個版本的代碼在 Python 2.7 上也沒有改變,並產生正確的結果。

暫無
暫無

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

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