#include <iostream>
unsigned char get_crc(unsigned char *packet) {
unsigned short POLY = 0x125;
unsigned short CARRY = 0x100;
unsigned char mask = 0x80;
unsigned short reg = 0;
for (int byte = 0; byte < 7; byte++) {
mask = 0x80;
for(int bit = 0; bit < 8; bit++) {
reg <<= 1;
if(packet[byte] & mask) reg |= 1;
mask >>=1;
if(reg & CARRY) reg^=POLY;
}
}
return reg & 0xFF;
}
int main() {
unsigned char packet[7] = {'1', 'h', 'e', 'l', 'l', 'o','0'};
unsigned char crc = get_crc(packet);
packet[6] = crc;
std::cout << "CRC: " << (int)crc << std::endl;
std::cout << (int)get_crc(packet) << std::endl;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgoKdW5zaWduZWQgY2hhciBnZXRfY3JjKHVuc2lnbmVkIGNoYXIgKnBhY2tldCkgewogIAogIHVuc2lnbmVkIHNob3J0IFBPTFkgID0gMHgxMjU7CiAgdW5zaWduZWQgc2hvcnQgQ0FSUlkgPSAweDEwMDsKICB1bnNpZ25lZCBjaGFyICBtYXNrICA9IDB4ODA7CiAgdW5zaWduZWQgc2hvcnQgcmVnICAgPSAwOwogIAogIGZvciAoaW50IGJ5dGUgPSAwOyBieXRlIDwgNzsgYnl0ZSsrKSB7CiAgICBtYXNrID0gMHg4MDsKICAgIGZvcihpbnQgYml0ID0gMDsgYml0IDwgODsgYml0KyspIHsKICAgICAgcmVnIDw8PSAxOwogICAgICBpZihwYWNrZXRbYnl0ZV0gJiBtYXNrKSByZWcgfD0gMTsKICAgICAgbWFzayA+Pj0xOwogICAgICBpZihyZWcgJiBDQVJSWSkgcmVnXj1QT0xZOwogICAgfQogIH0KICByZXR1cm4gcmVnICYgMHhGRjsgCn0KCmludCBtYWluKCkgewoJdW5zaWduZWQgY2hhciBwYWNrZXRbN10gPSB7JzEnLCAnaCcsICdlJywgJ2wnLCAnbCcsICdvJywnMCd9OwoJdW5zaWduZWQgY2hhciBjcmMgPSBnZXRfY3JjKHBhY2tldCk7CglwYWNrZXRbNl0gPSBjcmM7CglzdGQ6OmNvdXQgPDwgIkNSQzogIiA8PCAoaW50KWNyYyA8PCBzdGQ6OmVuZGw7CglzdGQ6OmNvdXQgPDwgKGludClnZXRfY3JjKHBhY2tldCkgPDwgc3RkOjplbmRsOwp9