Skip to content

Instantly share code, notes, and snippets.

@Shemeikka
Created July 10, 2015 08:46
Show Gist options
  • Save Shemeikka/a37baa691458b324bd86 to your computer and use it in GitHub Desktop.
Save Shemeikka/a37baa691458b324bd86 to your computer and use it in GitHub Desktop.
CRC16 in Go
type CRC16 struct {
Tab []uint16
Constant uint16
}
// Init crc16
func (c *CRC16) Init() {
c.Constant = 0xA001
for i := 0; i < 256; i++ {
crc := uint16(i)
for j := 0; j < 8; j++ {
if crc&0x0001 == 1 {
crc = crc>>1 ^ c.Constant
} else {
crc = crc >> 1
}
}
c.Tab = append(c.Tab, crc)
}
}
// Calculate CRC16
func (c *CRC16) Calculate(data []byte) uint16 {
var crcValue uint16 = 0x0000
for _, d := range data {
tmp := crcValue ^ uint16(d)
rotated := crcValue >> 8
crcValue = rotated ^ c.Tab[(tmp&0x00ff)]
}
return crcValue
}
c := CRC16{}
c.Init()
c.Calculate([]byte{})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment