Skip to content

Instantly share code, notes, and snippets.

@vbatts
Created January 16, 2017 21:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vbatts/95ee6ae704ad86eb22146b14b1d24489 to your computer and use it in GitHub Desktop.
Save vbatts/95ee6ae704ad86eb22146b14b1d24489 to your computer and use it in GitHub Desktop.
CRC-4 for golang
package crc4
func Checksum(b []byte) uint8 {
crc := 0xFFFF
for bI := 0; bI < len(b); bI++ {
bit := uint8(0x80)
for bitI := 0; bitI < 8; bitI++ {
xorFlag := ((crc & 0x8000) == 0x8000)
crc = crc << 1
if ((b[bI] & bit) ^ uint8(0xFF)) != uint8(0xFF) {
crc = crc + 1
}
if xorFlag {
crc = crc ^ 0x1021
}
bit = bit >> 1
}
}
return uint8(crc)
}
package crc4
import "testing"
func TestChecksum(t *testing.T) {
gold := []struct {
Data []byte
Checksum uint8
}{
{[]byte("apples and bananas"), 224},
{[]byte(":smiley_face:"), 247},
}
for _, i := range gold {
got := Checksum(i.Data)
if got != i.Checksum {
t.Errorf("expected %d; got %d", i.Checksum, got)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment