Skip to content

Instantly share code, notes, and snippets.

@KEINOS
Created April 20, 2023 02:28
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 KEINOS/cf29db0f87a303633c6966f4e84d970f to your computer and use it in GitHub Desktop.
Save KEINOS/cf29db0f87a303633c6966f4e84d970f to your computer and use it in GitHub Desktop.
[Golang] Example of Fletcher16 implementation in Go.

Example of Fletcher16 (Fletcher's checksum) in Go

package main

import "fmt"

// Fletcher16 returns the checksum of the data using the Fletcher's
// checksum algorithm.
func Fletcher16(data []byte) uint16 {
	sum1 := uint16(0)
	sum2 := uint16(0)

	for _, char := range data {
		sum1 = (sum1 + uint16(char)) % 0xff
		sum2 = (sum2 + sum1) % 0xff
	}

	return (sum2 << 8) | sum1
}

// IsValidFletcher16 returns true if the given checkSum is a valid check
// sum of the data.
func IsValidFletcher16(data []byte, checkSum uint16) bool {
	// Calculate check bytes from the checksum
	f0 := uint8(checkSum & 0xff)
	f1 := uint8((checkSum >> 8) & 0xff)

	c0 := 0xff - ((f0 + f1) % 0xff)
	c1 := 0xff - ((f0 + c0) % 0xff)

	return Fletcher16(append(data, c0, c1)) == 0
}

func Example() {
	for _, input := range [][]byte{
		[]byte("abcdef"),
		[]byte{0x01, 0x02},
		[]byte{0x01, 0x02, 0x03, 0x04},
	} {

		checkSum := Fletcher16(input)
		isValid := IsValidFletcher16(input, checkSum)

		fmt.Printf("Input: %#v\n\t-> Check SUM: 0x%04x, Verify: %v\n",
			string(input),
			checkSum,
			isValid,
		)
	}
	// Output:
	// Input: "abcdef"
	// 	-> Check SUM: 0x2057, Verify: true
	// Input: "\x01\x02"
	// 	-> Check SUM: 0x0403, Verify: true
	// Input: "\x01\x02\x03\x04"
	// 	-> Check SUM: 0x140a, Verify: true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment