Created
January 16, 2017 21:57
-
-
Save vbatts/95ee6ae704ad86eb22146b14b1d24489 to your computer and use it in GitHub Desktop.
CRC-4 for golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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