我正在编写一个程序来在 Groovy 中计算 CRC32。由于某种原因,我没有获得预期值(就像我使用 java.util.zip 实现一样):
def crc32(byte[] bytes) {
return new java.util.zip.CRC32().with { update bytes; value }
}
def myCrc32(byte[] bytes) {
def remainder = 0x0
def multiple = 0
def poly = 0xEDB88320
bytes.each { b ->
remainder ^= b
for (int i = 0; i < 8; i++) {
multiple = (remainder & 1) ? poly : 0;
remainder = (remainder >> 1) ^ multiple;
}
}
return remainder
}
def origFile = 'file'
def fileBytes = new File(origFile).text.getBytes()
def origRes = crc32(fileBytes)
def myRes = myCrc32(fileBytes)
println origRes
println myRes
我哪里做错了?我使用以下来源作为指导:
我得到的结果:
1838399800 - original
4005013284 - my calculation
最佳答案
好的,我自己解决了这个问题。
1) 作为基本余数
java.util.zip.Crc32
使用0xFFFFFFF。
2) 在通过与 0xFFFFFFF
进行异或运算给出答案之前,库实际上会翻转位。所以基本上我在 return
语句中添加了相同的 XOR 并得到了正确的答案。
关于java - CRC32 计算与默认计算不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40497291/