fork download
  1. #include <iostream>
  2.  
  3. unsigned char get_crc(unsigned char *packet) {
  4.  
  5. unsigned short POLY = 0x125;
  6. unsigned short CARRY = 0x100;
  7. unsigned char mask = 0x80;
  8. unsigned short reg = 0;
  9.  
  10. for (int byte = 0; byte < 7; byte++) {
  11. mask = 0x80;
  12. for(int bit = 0; bit < 8; bit++) {
  13. reg <<= 1;
  14. if(packet[byte] & mask) reg |= 1;
  15. mask >>=1;
  16. if(reg & CARRY) reg^=POLY;
  17. }
  18. }
  19. return reg & 0xFF;
  20. }
  21.  
  22. int main() {
  23. unsigned char packet[7] = {'1', 'h', 'e', 'l', 'l', 'o','0'};
  24. unsigned char crc = get_crc(packet);
  25. packet[6] = crc;
  26. std::cout << "CRC: " << (int)crc << std::endl;
  27. std::cout << (int)get_crc(packet) << std::endl;
  28. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
CRC: 106
48