Skip to content

Instantly share code, notes, and snippets.

@mrquincle
Created February 7, 2020 10:51
Show Gist options
  • Save mrquincle/ffab1d7e5ddadc150ec885305652ca7e to your computer and use it in GitHub Desktop.
Save mrquincle/ffab1d7e5ddadc150ec885305652ca7e to your computer and use it in GitHub Desktop.
CRC-CCITT (XModem)
#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