EN
JavaScript - calculate string crc32
8
points
In this short article, we would like to show how in a simple way calculate string CRC32 sum using JavaScript.
Practical example:
// ONLINE-RUNNER:browser;
const CRC_TABLE = Array(256);
for (let i = 0; i < 256; ++i) {
let code = i;
for (let j = 0; j < 8; ++j) {
code = (code & 0x01 ? 0xEDB88320 ^ (code >>> 1) : (code >>> 1));
}
CRC_TABLE[i] = code;
}
const crc32 = text => {
let crc = -1;
for (let i = 0; i < text.length; ++i) {
const code = text.charCodeAt(i);
crc = CRC_TABLE[(code ^ crc) & 0xFF] ^ (crc >>> 8);
}
return (-1 ^ crc) >>> 0;
};
// Usage example:
console.log(crc32('This is example text ...')); // 3473739588
Note: the solution calculates CRC32 using default strings encoding.
UTF-8 strings
In this section, you can find solution that lets to calculate CRC32 using UTF-8 encoded strings.
// ONLINE-RUNNER:browser;
// -- UTF-8
const toUtf8 = text => {
const input = encodeURIComponent(text);
let result = '';
for (let i = 0; i < input.length;) {
const character = input[i];
i += 1;
if (character == '%') {
const hex = input.substring(i, i += 2);
if (hex) {
result += String.fromCharCode(parseInt(hex, 16));
}
} else {
result += character;
}
}
return result;
};
// -- CRC32
const CRC_TABLE = Array(256);
for (let i = 0; i < 256; ++i) {
let code = i;
for (let j = 0; j < 8; ++j) {
code = (code & 0x01 ? 0xEDB88320 ^ (code >>> 1) : (code >>> 1));
}
CRC_TABLE[i] = code;
}
const crc32 = text => {
const input = toUtf8(text);
let crc = -1;
for (let i = 0; i < input.length; ++i) {
const code = input.charCodeAt(i);
crc = CRC_TABLE[(code ^ crc) & 0xFF] ^ (crc >>> 8);
}
return (-1 ^ crc) >>> 0;
};
// Usage example:
console.log(crc32('日本')); // 3350711756
console.log(crc32('I ❤️ JS')); // 676906920
console.log(crc32('This is example text ...')); // 3473739588