crc16/crc.go

33 lines
563 B
Go
Raw Normal View History

package crc16
var Crc16Table = make([]uint16, 256)
const GeneratorPolynomial = 0x1021
func init() {
calculateTable()
}
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
}
}
func Calculate(data []byte) uint16 {
crc := uint16(0)
for _, b := range data {
pos := byte(crc>>8) ^ b
crc = (crc << 8) ^ Crc16Table[pos]
}
return crc
}