diff --git a/README.md b/README.md index 6a263a8..99fe924 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,5 @@ # crc16 +An CRC-16 implementation + +Made with this https://www.sunshine2k.de/articles/coding/crc/understanding_crc.html#ch4 tutorial. \ No newline at end of file diff --git a/crc.go b/crc.go new file mode 100644 index 0000000..b325db5 --- /dev/null +++ b/crc.go @@ -0,0 +1,32 @@ +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 +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..66de3f3 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module git.barfuss.email/jan/crc16 + +go 1.22.1