-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtils.ts
More file actions
78 lines (64 loc) · 1.79 KB
/
Utils.ts
File metadata and controls
78 lines (64 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import {type BufferAccess} from './BufferAccess.js';
export function calculateChecksum8(data: BufferAccess) {
let sum = 0;
for (let i = 0; i < data.length(); i++) {
sum = (sum + data.getUint8(i)) & 0xff;
}
return sum;
}
export function calculateChecksum16Le(data: BufferAccess) {
let sum = 0;
for (let i = 0; i < data.length(); i += 2) {
sum = (sum + data.getUint16Le(i)) & 0xffff;
}
return sum;
}
export function calculateChecksum8Xor(ba: BufferAccess, initial = 0x00) {
let sum = initial;
for (let i = 0; i < ba.length(); i++) {
sum ^= ba.getUint8(i);
}
return sum;
}
export function calculateChecksum8WithCarry(ba: BufferAccess) {
// 8 bit checksum with carry being added
let sum = 0;
for (let i = 0; i < ba.length(); i++) {
sum += ba.getUint8(i);
if (sum > 255) {
sum = (sum & 0xff) + 1;
}
}
return sum;
}
/**
* https://gist.github.com/chitchcock/5112270?permalink_comment_id=3834064#gistcomment-3834064
*
* Used by Amstrad CPC and IBM PC 5150.
*/
export function calculateCrc16Ccitt(ba: BufferAccess): number {
const polynomial = 0x1021;
let crc = 0xffff;
for (let n = 0; n < ba.length(); n++) {
const b = ba.getUint8(n);
for (let i = 0; i < 8; i++) {
const bit = (b >> (7 - i) & 1) === 1;
const c15 = (crc >> 15 & 1) === 1;
crc <<= 1;
if (c15 !== bit) {
crc ^= polynomial;
}
}
}
crc &= 0xffff;
return crc ^ 0xffff; // The negation is not part of the actual CRC16-CCITT code.
}
export function hex8(value: number): string {
return `0x${value.toString(16).padStart(2, '0')}`;
}
export function hex16(value: number): string {
return `0x${value.toString(16).padStart(4, '0')}`;
}
export function hex32(value: number): string {
return `0x${value.toString(16).padStart(8, '0')}`;
}