Skip to content

Instantly share code, notes, and snippets.

@jackhftang
Created October 25, 2019 13:35
Show Gist options
  • Save jackhftang/41841838cfe1663395fb02a4385b29b8 to your computer and use it in GitHub Desktop.
Save jackhftang/41841838cfe1663395fb02a4385b29b8 to your computer and use it in GitHub Desktop.
fletcher
proc fletcher16*(arr: openArray[uint8]): uint16 =
var
c1: int = 0
c2: int = 0
for d in arr:
c1 += d.int
c2 += c1
result = (((c2 mod 255) shl 8) + (c1 mod 255)).uint16
import unittest
import fletcher
suite "fletcher":
test "fletcher16":
# https://en.wikipedia.org/wiki/Fletcher%27s_checksum#Test_vectors
check: fletcher([97.byte,98,99,100,101]) == 51440.uint16
check: fletcher([97.byte,98,99,100,101,102]) == 8279.uint16
check: fletcher([97.byte,98,99,100,101,102,103,104]) == 1575.uint16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment