我必须将文件与 java 和 C# 脚本提供的 CRC32 代码进行比较。当我用 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 < 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# 脚本...
您会发现此代码片段很有用:
- http://www.cs.princeton.edu/introcs/51data/CRC32.java.html http://www.cs.princeton.edu/introcs/51data/CRC32.java.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)