如何将这个Python2代码转换成Python3?

2024-10-03 13:27:23 发布

您现在位置:Python中文网/ 问答频道 /正文

转换此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中,上述代码的结果是“A071C58205EC529C5C19FA7DADCAE93”。但是,当我尝试使用hashlib库在Python3中重现相同的代码时,得到的结果完全不同。我希望它返回与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”,这不是我希望它返回的


Tags: 代码inimportnewforrangebetemp
1条回答
网友
1楼 · 发布于 2024-10-03 13:27:23

在Python3中,您使用正确的代码点构建字符串,然后使用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())

作为一个额外的好处,这个版本的代码在Python2.7上也运行不变,并生成正确的结果

相关问题 更多 >