Java CRC32 : not the same as CRC from C#

标签 java crc

我必须将文件与 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;
        }
    }
}

非常感谢, 弗兰克

最佳答案

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

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

关于Java CRC32 : not the same as CRC from C# ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4344190/

相关文章:

java - 我的 Android 应用程序的多任务处理速度缓慢

java - 不使用 String API 时获取号码中的位数

java - 为什么我们在发现 @Inject 方法时会遇到 StackOverflowError ?

java - java中的最终变量和同步块(synchronized block)

vb6 - CRC计算错误输出

java - 在创建新对象时是否应该始终使用 "this"作为上下文?

javascript - delphi中生成的crc与javascript中的crc不同

c# - PNG CRC 是如何精确计算的?

具有已知 CRC 的级联输入的 CRC

math - 为什么 CRC 32 生成器不能被 11 整除?