Java CRC32:与C#中的CRC不同

我必须将带有java的文件与C#脚本提供的C​​RC32代码进行比较。 当我用java.util.zip.CRC32计算CRC32时,结果完全不同……

我的猜测是C#脚本的多项式= 0x2033与zip.CRC32中使用的不同。 是否可以设置多项式? 或者用于计算CRC32的java类的任何想法,您可以在其中定义自己的多项式?

更新:问题不是多态。 这在C#和Java之间是相同的

这是我的代码,也许我读取文件的方式有问题?

package com.mine.digits.internal.contentupdater; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.CRC32; public class CRC { public static String doConvert32(File file) { byte[] bytes = readBytesFromFile(file); // readFromFile(file).getBytes(); CRC32 x = new CRC32(); x.update(bytes); return (Long.toHexString(x.getValue())).toUpperCase(); } /** Read the contents of the given file. */ private static byte[] readBytesFromFile(File file) { try { InputStream is = new FileInputStream(file); long length = file.length(); if (length > Integer.MAX_VALUE) { // File is too large } byte[] bytes = new byte[(int)length]; int offset = 0; int numRead = 0; while (offset = 0) { offset += numRead; } // Ensure all the bytes have been read in if (offset < bytes.length) { System.out.println("Could not completely read file " + file.getName()); } // Close the input stream and return bytes is.close(); return bytes; } catch (IOException e) { System.out.println("IOException " + file.getName()); return null; } } } 

非常感谢,弗兰克

标准(IEEE)CRC32多项式为0x04C11DB7 ,对应于:

 x^32 + x^26 + x^23 + x^22 + x^16 + x^12 + x^11 + x^10 + x^8 + x^7 + x^5 + x^4 + x^2 + x + 1 

这就是java.util.zip.CRC32使用的内容。 不知道你提到的C#脚本……

您可以找到以下代码段:

CRC-32是根据IEEE 802.3的特定CRC变体,并且使用多项式0x04C11DB7。 如果您的C#库使用的是多项式0x2033,则它/不是CRC-32的实现。

如果您需要Java代码来计算任意CRC变体,Google搜索“java crc”将为您提供几个示例。

通过从C#复制代码并将其转换为Java类来解决…

所以现在两者都使用相同的代码,只需要对无符号<>有符号字节差异进行一些小的改动。

1 + x + x ^ 2 + x ^ 4 + x ^ 5 + x ^ 7 + x ^ 8 + x ^ 10 + x ^ 11 + x ^ 12 + x ^ 16 + x ^ 22 + x ^ 23 + x ^ 26(0x04C11DB7)Java使用上述多项式进行CRC 32计算,并且不同于IEEE 802.3标准,其另外具有32位x的幂。