From 61a5eb603992959101f5cdb51b78ec90dd75acd7 Mon Sep 17 00:00:00 2001 From: David Lechner Date: Wed, 10 Jun 2020 19:03:45 -0500 Subject: [PATCH] add xor8 checksum we are starting with 0xff like all known LEGO checksums of this style. --- src/utils/math.test.ts | 14 +++++++++++++- src/utils/math.ts | 13 +++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/utils/math.test.ts b/src/utils/math.test.ts index 2e870f38..eaa60641 100644 --- a/src/utils/math.test.ts +++ b/src/utils/math.test.ts @@ -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); + }); +}); diff --git a/src/utils/math.ts b/src/utils/math.ts index 63e9f7bc..0b2c7445 100644 --- a/src/utils/math.ts +++ b/src/utils/math.ts @@ -28,3 +28,16 @@ export function sumComplement32(data: Iterable): 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 { + let checksum = 0xff; + for (const n of data) { + checksum ^= n & 0xff; + } + return checksum; +}