EN
TypeScript - calculate crc32
3 points
In this short article, we would like to show how in a simple way calculate CRC32 sum using TypeScript.
Practical example:
xxxxxxxxxx
1
const CRC_TABLE: number[] = Array(256);
2
3
for (let i = 0; i < 256; ++i) {
4
let code = i;
5
for (let j = 0; j < 8; ++j) {
6
code = code & 0x01 ? 0xedb88320 ^ (code >>> 1) : code >>> 1;
7
}
8
CRC_TABLE[i] = code;
9
}
10
11
const crc32 = (text: string): number => {
12
let crc = -1;
13
for (let i = 0; i < text.length; ++i) {
14
const code = text.charCodeAt(i);
15
crc = CRC_TABLE[(code ^ crc) & 0xff] ^ (crc >>> 8);
16
}
17
return (-1 ^ crc) >>> 0;
18
};
19
20
21
// Usage example:
22
23
console.log(crc32('This is example text ...')); // 3473739588
Output:
xxxxxxxxxx
1
3473739588