I have the follow CRC function:
unsigned long Checksummer::crc32 (unsigned long crc, char *buf, unsigned long len)
{
unsigned long crc_table[256];
int i, k;
for (i = 0; i < 256; i++) {
unsigned long c = (unsigned long) i;
for (k = 0; k < 8; k++)
c = c & 1 ? 0xedb88320 ^ (c >> 1) : c >> 1;
crc_table[i] = c;
}
crc = crc ^ 0xffffffffL;
while (len--)
crc = crc_table[((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8);
return crc ^ 0xffffffffL;
}
I am trying to port this code to Java so that I can calculate CRCs on multiple platforms. My ported code below produces a different result. What am I doing wrong?
static long getCrc32 (long crc, char[] buf, long len)
{
long crc_table[] = new long[256];
int i, k;
for (i = 0; i < 256; i++) {
long c = ( long)i;
for (k = 0; k < 8; k++)
c = (c & 1) == 1 ? 0xedb88320 ^ (c >> 1) : c >> 1;
crc_table[i] = c;
}
/* Calculate crc on buf */
crc = crc ^ 0xffffffffL;
int j = 0;
while (len-- != 0){
crc = crc_table[((int)crc ^ (buf[(int)j++])) & 0xff] ^ (crc >> 8);}
return crc ^ 0xffffffffL;
}
charis two bytes in Java; usebyteinstead (charin C and C++ are one byte by definition).longis eight bytes in Java; useintinstead (assumingsizeof(unsigned long) == 4on your C++ platform, which is the norm).