JavaScript CRC32

后端 未结 6 1331
暖寄归人
暖寄归人 2020-12-02 07:05

I\'m looking for a modern JavaScript implementation of CRC32.

This implementation, which may have originated from here, and is now here, there and e

6条回答
  •  春和景丽
    2020-12-02 07:47

    I needed this ASAP so I wrote my own. Hope someone finds it useful.
    196 bytes (After closure compiler). 16ms/MB

    Edit: With improvements from everyone’s input.

    var crc32 = (function()
    {
        var table = new Uint32Array(256);
    
        // Pre-generate crc32 polynomial lookup table
        // http://wiki.osdev.org/CRC32#Building_the_Lookup_Table
        // ... Actually use Alex's because it generates the correct bit order
        //     so no need for the reversal function
        for(var i=256; i--;)
        {
            var tmp = i;
    
            for(var k=8; k--;)
            {
                tmp = tmp & 1 ? 3988292384 ^ tmp >>> 1 : tmp >>> 1;
            }
    
            table[i] = tmp;
        }
    
        // crc32b
        // Example input        : [97, 98, 99, 100, 101] (Uint8Array)
        // Example output       : 2240272485 (Uint32)
        return function( data )
        {
            var crc = -1; // Begin with all bits set ( 0xffffffff )
    
            for(var i=0, l=data.length; i>> 8 ^ table[ crc & 255 ^ data[i] ];
            }
    
            return (crc ^ -1) >>> 0; // Apply binary NOT
        };
    
    })();
    

提交回复
热议问题