Languages
[Edit]
EN

JavaScript - calculate string crc32

8 points
Created by:
Reilly-Collier
860

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

 

See also

  1. TypeScript - calculate crc32
  2. JavaScript - strings default encoding

  3. JavaScript - convert string to bytes array (UTF-8)

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join