我有一个二进制文件(2字节),其十六进制格式的内容如下:
00 00 00 DD 11 22 33 44
在二进制中,内容如下所示(小端格式):
11011101 00000000 00000000 00000000 01000100 00110011 00100010 00010001
我想手动计算文件的校验和并将其附加到文件末尾。对于计算,我考虑一次使用 4 个字节 block 。
那么手动步骤应如下所示:
11011101 00000000 00000000 00000000
+
01000100 00110011 00100010 00010001
--------------------------------------
= 00100001 00110011 00100010 00010001
11011110 11001100 11011101 11101110 (1's complement)
+
00000000 00000000 00000000 00000001 (add 1) <br/>
-----------------------------------------
= 11011110 11001100 11011101 11101111 (2's complement) = CheckSum
如果我错误地计算了校验和,请纠正我。 我编写的用于计算系统中校验和的代码无法正常工作。
add = 0
with open("temp.bin", "rb") as f:
## Read first 4 bytes of data
byte = f.read(4)
while byte != "":
add += int.from_bytes(byte, byteorder="little")
print(b"%02X" % (~add & 0xFFFFFFFF))
请帮我解决上述问题和代码。
最佳答案
您没有在 while
循环中更新 byte
,因此循环永远不会结束。
您应该继续从 f
开始读取,直到 byte
为 None
:
add = 0
with open("/temp/test.py", "rb") as f:
## Read first 4 bytes of data
while True:
byte = f.read(4)
if not byte:
break
add += int.from_bytes(byte, byteorder='little')
print(b'%02X' % (~add & 0xFFFFFFFF))
关于python - 在 Python 中计算二进制文件的校验和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51666455/