// CRC16 implements the CRC-16-CCITT algorithm. // The polynomial is 0x1021. // It accepts a byte slice and returns a 16-bit checksum. package crc16 var Crc16Table = make([]uint16, 256) // GeneratorPolynomial is the polynomial used in the CRC-16-CCITT algorithm. const GeneratorPolynomial = 0x1021 func init() { calculateTable() } // calculateTable computes the CRC-16 lookup table. // The table is used to speed up the CRC calculation. func calculateTable() { for dividend := 0; dividend < 256; dividend++ { crc := uint16(dividend << 8) for bit := 0; bit < 8; bit++ { if (crc & 0x8000) != 0 { crc = (crc << 1) ^ GeneratorPolynomial } else { crc <<= 1 } } Crc16Table[dividend] = crc } } // Calculates generates a CRC-16 checksum for the given data. // It accepts a byte slice and returns a 16-bit checksum. func Calculate(data []byte) uint16 { crc := uint16(0) for _, b := range data { pos := byte(crc>>8) ^ b crc = (crc << 8) ^ Crc16Table[pos] } return crc }