( SimplyCalc )    Calculate, Compute and Convert.  Simply.

JavaScript CRC-32 Source Code

Compute CRC-32 cyclic redundancy check. This implementation allows using any custom polynomial. The crc32_generate() function first generates a polynomial-derived table for faster CRC-32 computation.

This source code is in the public domain. You may use, share, modify it freely, without any conditions or restrictions.

Download source code:

See it in action, try it online now:

See also JavaScript source code for base64, Luhn.

Source Code

/*
 * JavaScript CRC-32 implementation
 */

function crc32_generate(polynomial) {
    var table = new Array()
    var i, j, n
    
    for (i = 0; i < 256; i++) {
        n = i
        for (j = 8; j > 0; j--) {
            if ((n & 1) == 1) {
                n = (n >>> 1) ^ polynomial
            } else {
                n = n >>> 1
            }
        }
        table[i] = n
    }

    return table
}

function crc32_initial() {
    return 0xFFFFFFFF
}

function crc32_final(crc) {
    crc = ~crc
    return crc < 0 ? 0xFFFFFFFF + crc + 1 : crc
}

function crc32_compute_string(polynomial, str) {
    var crc = 0
    var table = crc32_generate(polynomial)
    var i
    
    crc = crc32_initial()
    
    for (i = 0; i < str.length; i++)
        crc = (crc >>> 8) ^ table[str.charCodeAt(i) ^ (crc & 0x000000FF)]
        
    crc = crc32_final(crc)
    return crc
}

function crc32_compute_buffer(polynomial, data) {
    var crc = 0
    var dataView = new DataView(data)
    var table = crc32_generate(polynomial)
    var i
    
    crc = crc32_initial()
    
    for (i = 0; i < dataView.byteLength; i++)
        crc = (crc >>> 8) ^ table[dataView.getUint8(i) ^ (crc & 0x000000FF)]
        
    crc = crc32_final(crc)
    return crc
}