add xor8 checksum

we are starting with 0xff like all known LEGO checksums of this style.
This commit is contained in:
David Lechner
2020-06-10 21:59:34 -05:00
committed by David Lechner
parent 818e7867ee
commit 61a5eb6039
2 changed files with 26 additions and 1 deletions
+13 -1
View File
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: MIT
// Copyright (c) 2020 The Pybricks Authors
import { fmod, sumComplement32 } from './math';
import { fmod, sumComplement32, xor8 } from './math';
describe('fmod', () => {
test('positive numbers', () => {
@@ -21,3 +21,15 @@ describe('sumComplement32', () => {
expect(sumComplement32([0xffffffff, 0xffffffff])).toBe(-(-1 + -1));
});
});
describe('xor8', () => {
test('basic', () => {
expect(xor8([0])).toBe(0xff);
});
test('basic2', () => {
expect(xor8([0xff, 0xff, 0xff])).toBe(0);
});
test('basic3', () => {
expect(xor8([0xc0, 0x0c])).toBe(0x33);
});
});
+13
View File
@@ -28,3 +28,16 @@ export function sumComplement32(data: Iterable<number>): number {
// checksum is two's complement of total
return ~total + 1;
}
/**
* Calculates the 8-bit "xor" checksum
* @data an iterable of 8-bit integers
* @returns all of the values xored together along with 0xff
*/
export function xor8(data: Iterable<number>): number {
let checksum = 0xff;
for (const n of data) {
checksum ^= n & 0xff;
}
return checksum;
}