First implementation - untested, v0.1.0

This commit is contained in:
Jan Barfuss 2025-01-12 01:17:24 +01:00
parent 4d58212d07
commit aca90bba91
3 changed files with 38 additions and 0 deletions

View File

@ -1,2 +1,5 @@
# crc16 # crc16
An CRC-16 implementation
Made with this https://www.sunshine2k.de/articles/coding/crc/understanding_crc.html#ch4 tutorial.

32
crc.go Normal file
View File

@ -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
}

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module git.barfuss.email/jan/crc16
go 1.22.1