Created
February 7, 2020 10:51
-
-
Save mrquincle/ffab1d7e5ddadc150ec885305652ca7e to your computer and use it in GitHub Desktop.
CRC-CCITT (XModem)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <iomanip> | |
uint16_t crcTable[256]; | |
#define WIDTH (8 * sizeof(uint16_t)) | |
#define TOPBIT (1 << (WIDTH - 1)) | |
// Checked with https://www.lammertbies.nl/comm/info/crc-calculation | |
// It is CRC-CCITT (XModem) | |
// Use other polynomial to get other results | |
#define POLYNOMIAL 0x1021 | |
void crcInit(void) | |
{ | |
uint16_t remainder; | |
for (int dividend = 0; dividend < 256; ++dividend) { | |
remainder = dividend << (WIDTH - 8); | |
// modulo-2 division, a bit at a time. | |
for (uint8_t bit = 8; bit > 0; --bit) { | |
if (remainder & TOPBIT) { | |
remainder = (remainder << 1) ^ POLYNOMIAL; | |
} else { | |
remainder = (remainder << 1); | |
} | |
} | |
crcTable[dividend] = remainder; | |
} | |
} | |
int main() { | |
crcInit(); | |
// with 0x (use setw(6) in that case: including 0x digits) | |
//std::cout << std::showbase << std::internal << std::setfill('0'); | |
// without | |
std::cout << std::setfill('0') << std::setw(4); | |
for (int i = 0; i < 256; ++i) { | |
std::cout << std::setw(4) << std::hex << crcTable[i] << std::endl; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment