mirror of
https://github.com/pybricks/pybricks-code.git
synced 2026-09-12 01:23:52 +00:00
add xor8 checksum
we are starting with 0xff like all known LEGO checksums of this style.
This commit is contained in:
committed by
David Lechner
parent
818e7867ee
commit
61a5eb6039
+13
-1
@@ -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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user