2

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

我的猜测是 C# 脚本的 polynom = 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 < bytes.length && (numRead=is.read(bytes, offset, bytes.length-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;
        }
    }
}

非常感谢,弗兰克

4

4 回答 4

3

标准 (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#脚本...

您会发现此代码段很有用:

于 2010-12-03T10:20:15.030 回答
1

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

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

于 2010-12-03T10:28:07.707 回答
0

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 标准不同,IEEE 802.3 标准还具有 x 的 32 位幂。

于 2014-09-08T05:02:53.920 回答
0

Solved by copying the code from C# and convert it to a Java-class...

So now both use the same code, only had to do some minor changes for unsigned <> signed bytes differences.

于 2010-12-09T09:53:54.590 回答