我正在编写一个简单的哈希函数,它获取输入并创建一个 32 位哈希文件。我陷入了异或部分。我不确定应该如何编写异或函数。请在这件事上给予我帮助。这是我已经完成的代码:
import BitVector
import io
import math
import struct
if __name__ == "__main__":
message = raw_input("your message:")
f= open('file.dat','w')
f.write(message)
f.close()
f = open('file.dat')
while 1:
r = f.readline(1)
hx = r.encode("hex")
data = bin(int(hx, 16))[2:]
key = 11111111
x = int(data) ^ int(key)
print hex(x)
if not r:break
f.close()
最佳答案
运算符 ^
对您来说已经足够了。
>>> 2 ^ 1
3
>>> 3 ^ 1
2
您应该关心的是 key 的位大小和“异或”数据的位大小,以确保功能。
顺便说一句,异或运算应该只适用于整数。
import struct
key = 0xFEEEFEEE
with open('file', 'rb') as f:
integer = f.read(4) # In fact, you could read all in.
while len(integer) >= 4:
# if integer is not a string longer than 4, next line crash.
s, = struct.unpack('i', integer) # The return value is a tuple with integers.
print key ^ s
integer = f.read(4)
关于python - 在 python 中对二进制文件进行异或,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9372111/