I've read the famous article A PAINLESS GUIDE TO CRC ERROR DETECTION ALGORITHMS, now I want to try this out. I'm using a nodejs module node-crc, it looks easy to use:
var crc = require('crc');
crc.crc32('hello');
# => "3610a686"
The result of function crc32
, I believe, is the checksum of hello
using polynomial 0x04C11DB7
. Please correct me if I' wrong.
So the next step is appending the checksum to the original data. Here's my code:
var crc = require('crc');
var bf = Buffer("test");
charlist = crc.crc32(bf).toString();
var k = []
for (var i=0; i< 8; i++) {
k.push(parseInt(charlist[i], 16));
}
console.log(k)
var checksum = Buffer(k);
console.log(crc.crc32(Buffer.concat([bf, checksum])));
output
[ 13, 8, 7, 15, 7, 14, 0, 12 ]
646b4f9b
I'm expecting the second output to be 0
, but it's not.
Therefore I'm here asking for help. What is the correct way to do this(appending and checking if the message was correctly received)? Thank you.
So I understand that the second output isn't necessarilly 0
. Here's the final solution:
var crc = require('crc');
var bf = Buffer("test");
charlist = crc.crc32(bf).toString();
var k = []
for (var i=0; i< 8; i++) {
k.push(parseInt(charlist[i], 16));
}
var checksum = Buffer(k);
transfer_data = Buffer.concat([bf, checksum]);
////////////////////// Network Transfer /////////////////////////
received_data = transfer_data
checksum = received_data.slice(-8);
charlist = '';
for (var i=0; i<8; i++) {
charlist += checksum.readUInt8(i).toString(16);
}
// these two should be equal if data received correctly
console.log(crc.crc32(received_data.slice(0, -8)));
console.log(charlist)
Output
d87f7e0c
d87f7e0c
Yes, the crc32
function uses the polynomial you quoted, but it also is pre and post processed by taking the one's complement. That eliminates the property that the (pure) CRC of a message with its CRC appended is zero.
The correct way to check a CRC, which is extensible to any manner of check value, is to simply compute the specified check algorithm on the message, and then compare the result with the check value appended to the message.