转换此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”,这不是我希望它返回的
在Python3中,您使用正确的代码点构建字符串,然后使用
encode()
将其转换为字节。这就是问题所在:encode()
将UTF8编码字符串中的代码点,这将导致字节序列与预期的不同。为了避免此问题,您应该从头开始使用字节:作为一个额外的好处,这个版本的代码在Python2.7上也运行不变,并生成正确的结果
相关问题 更多 >
编程相关推荐