I am trying to calculate CRC32 checksum in C++. But i'm still getting bad results.
C++ code:
class CRC32
{
public:
CRC32() {
unsigned int poly = 0xedb88320;
unsigned int temp = 0;
for(unsigned int i = 0; i < 256; ++i) {
temp = i;
for(int j = 8; j > 0; --j) {
if((temp & 1) == 1) {
temp = (unsigned int)((temp >> 1) ^ poly);
}else {
temp >>= 1;
}
}
table[i] = temp;
}
}
unsigned int ComputeChecksum(byte* bytes,size_t size) {
unsigned int crc = 0xffffffff;
for(int i = 0; i < size; ++i) {
byte index = (byte)(((crc) & 0xff) ^ bytes[i]);
crc = (unsigned int)((crc >> 8) ^ table[index]);
}
return ~crc;
}
private:
unsigned int table[256];
};
This java code works fine:
private int stmCrc32(byte abyte0[])
{
CRC32 crc32 = new CRC32();
crc32.update(abyte0);
return (int)(-1L ^ crc32.getValue());
}
This is hex string of example data (result should be 1909660290):
00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:01:00:12:00:59:57:52:74:61:57:34:36:59:57:52:74:61:57:34:3d:0d:0a:00:00
The two implementations appear to be identical. You just missed out in the surrounding code. In C++, do exactly what they did in Java (however dumb that may be), and the result will be the same.
byte data[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x12, 0x00, 0x59, 0x57, 0x52, 0x74, 0x61, 0x57, 0x34, 0x36, 0x59, 0x57, 0x52, 0x74, 0x61, 0x57, 0x34, 0x3d, 0x0d, 0x0a, 0x00, 0x00};
CRC32 crc;
int result = (int)(-1L ^ crc.ComputeChecksum(data, sizeof(data)));
std::cout << result << std::endl;
Result: 1909660290