Java CRC32:与C#中的CRC不同 [英] Java CRC32: not the same as CRC from C#

查看:247
本文介绍了Java CRC32:与C#中的CRC不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to compare files with java with a CRC32 code provided by a C# script. When I calculate the CRC32 with java.util.zip.CRC32 the result is completely different ...

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

My guess is that the polynom = 0x2033 of the C# script is not the same as used in zip.CRC32. Is it possible to set the polynom ? Or any ideas of a java-class for calculating a CRC32 where you can define your own polynom?

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

UPDATE: problem is not the polymnom. This is the same between C# and Java

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

This is my code, maybe something is wrong in the way I read the file?

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;
        }
    }
}

非常感谢,
Frank

Thanks a lot, Frank

推荐答案

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

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.

这篇关于Java CRC32:与C#中的CRC不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆