![](/img/trans.png)
[英]Is there any difference in calculating CRC32 checksum in C# and Java?
[英]Java CRC32: not the same as CRC from C#
我必須使用C#腳本提供的CRC32代碼將文件與Java進行比較。 當我使用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#腳本...
您可以找到以下有用的代碼段:
CRC-32是根據IEEE 802.3的特定CRC變體,並使用多項式0x04C11DB7。 如果您的C#庫使用的是多項式0x2033,則它是/ not / CRC-32的實現。
如果您需要Java代碼來計算任意的CRC變體,則使用Google搜索“ java crc”將為您提供一些示例。
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。
通過從C#復制代碼並將其轉換為Java類來解決...
因此,現在兩者都使用相同的代碼,只需要對無符號<>有符號字節的差異進行一些小的更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.