First implementation - untested, v0.1.0
This commit is contained in:
parent
4d58212d07
commit
aca90bba91
@ -1,2 +1,5 @@
|
||||
# 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
32
crc.go
Normal 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
|
||||
}
|
Loading…
Reference in New Issue
Block a user