问题
My problem is when using this implementation; the Java CRC32 calculation is different from C#'s CRC32 calculation using a look-up table.
The following is the CRC32 code I am using:
public static int CalculateCRCWithTable(byte[] data){
int crc = 0;
for (byte b : data) {
crc = CRCTable[(crc & 0xff) ^ (b & 0xff)] ^ (crc >>> 8) ;
}
//crc = crc ^ 0xffffffff; // flip bit/sign
return (crc);
}
Reading from file:
public static byte[] readFromFileToByteArray(String fileName) throws IOException {
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(fileName));
byte [] bytes = IOUtils.toByteArray(fis);
for (byte b : bytes){
b = (byte) (b & 0xff);
}
return bytes;
}
When testing the Java CRC32 calculation with a simple text file the CRC calculation is (sometimes) correct as in identical to C#'s, but pointing to an executable/binary file then I start seeing different results.
(Moving sample data from comment into question section): String: "simple CRC32 calculation test" Hexadecimal value:
73 69 6D 70 6C 65 20 43 52 43 33 32 20 63 61 6C 63 75 6C 61 74 69 6F 6E 20 74 65 73 74
Both implemented with look-up table:
- "Expected/Correct" C#'s CRC32 calc: 3347067236
- Java CRC32 calc : -947900060
In a similar thread someone mentioned implementing unsigned integer 32 for Java should fix the difference.
Any pointers would be greatly appreciated and thank you.
SOLVED: Thank you Mark for your verification! With that in mind the below was just needed to get the right CRC32 calc:
String tmp = Integer.toHexString(crc);
long lCRC = Long.parseLong(tmp, 16);
回答1:
The two values you provided in your comment (they should be moved to the question) are exactly equal in their low 32 bits. 3347067236 = 232 - 947900060. They are both 0xc7803164. You don't have a problem.
来源:https://stackoverflow.com/questions/14187955/yet-another-java-crc32-implementation-related-issue