Algorithm Alley by Tim Kientzle Listing One short BitwiseCrc16(int bit, short crc) { long longcrc = crc; longcrc = (longcrc << 1) ^ bit; /* next bit */ if (longcrc & 0x10000) longcrc ^= 0x11021; /* reduce */ return(longcrc & 0xFFFF); } Listing Two short BitwiseCrc16(int bit, short crc) { if (crc & 0x8000) crc = (crc << 1) ^ bit ^ 0x1021 ; else crc = (crc << 1) ^ bit; return (crc & 0xffff); } Listing Three static short Crc16Table[256]; void InitCrc16() { short i, j, crc; for(i=0; i < 256; i++) { crc = (i << 8); /* Put i into MSB */ for(j=0; j < 8; j++) /* Do 8 reductions */ crc = (crc << 1) ^((crc & 0x8000)? 0x1021:0); Crc16Table[i] = crc & 0xFFFF; } } short Crc16(int ch, short crc) { crc = Crc16Table[((crc >> 8) & 255)] ^ (crc << 8) ^ ch; return crc & 0xFFFF; } Listing Four /* InitCrc16() is same as Listing Three */ short XYZModemCrc16(int ch, short crc) { crc = Crc16Table[((crc >> 8) ^ ch) & 255] ^ (crc << 8); return crc & 0xFFFF; } Listing Five static short KermitCrc16Table[256]; void KermitInitCrc16() { int i, j, crc; for(i=0; i <256; i++) { crc = i; /* Start with i in low-order byte */ for(j=0; j < 8; j++) crc = (crc >> 1) ^ ((crc & 1) ? 0x8408 : 0); KermitCrc16Table[i] = crc & 0xFFFF; } } short KermitCrc16(int ch, short crc) { crc = KermitCrc16Table[(crc ^ ch) & 255)] ^ (crc >> 8); return crc & 0xFFFF; } Listing Six static long Crc32Table[256]; InitCrc32() { int i, j; long crc; for(i=0; i <256; i++) { crc = (i << 24); /* Put i into MSB */ for(j=0; j < 8; j++) /* 8 reductions */ crc = (crc << 1) ^ ((crc & 0x80000000L) ? 0x04c11db7L : 0); Crc32Table[i] = crc; } } long Crc32(int ch, long crc) { crc = Crc32Table[((crc >> 24) ^ ch) & 255] ^ (crc << 8); return crc & 0xFFFFFFFF; } 2