JavaScript CRC32 [英] JavaScript CRC32

查看:219
本文介绍了JavaScript CRC32的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找CRC32的现代 JavaScript实现。

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

此实现,可能源自这里,现在在这里,那里无处不在,是不可接受的,因为它很慢(500ms / MB),并依赖于超过2KB的空格分隔表,使用substr访问。 Yuck!

This implementation, which may have originated from here, and is now here, there and everywhere, is unacceptable because it's slow (500ms/MB), and depends on over 2KB of space delimited table, accessed using substr. Yuck!

CRC32似乎有一些变化,所以我需要匹配这个输出:

There appears to be a few variations of CRC32, so I need to match this output:

mysql> SELECT CRC32('abcde');
> 2240272485

函数实际上并不需要接受字符串,因为我正在使用字节数组。

Function doesn't actually need to accept a string however, since I'm working with byte arrays.

推荐答案

更新



我添加了一个辅助函数来创建CRCTable而不是代码中有这么大的文字。它也可以用来创建一次表并将其保存在一个对象或变量中,并让crc32函数使用它(或者作为W3C的例子,检查存在并在必要时创建)。我还更新了jsPerf以使用CRCtable与文字字符串,文字数组,保存的窗口变量和动态指针(此处显示的示例)进行比较。

Update

I added a helper function to create the CRCTable instead of having this enormous literal in the code. It could also be used to create the table once and save it in an object or variable and have the crc32 function use that (or as W3C's example, check for the existence and create if necessary). I also updated the jsPerf to compare using a CRCtable with the literal string, literal array, saved window variable and dynamic pointer (the example shown here).

var makeCRCTable = function(){
    var c;
    var crcTable = [];
    for(var n =0; n < 256; n++){
        c = n;
        for(var k =0; k < 8; k++){
            c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
        }
        crcTable[n] = c;
    }
    return crcTable;
}

var crc32 = function(str) {
    var crcTable = window.crcTable || (window.crcTable = makeCRCTable());
    var crc = 0 ^ (-1);

    for (var i = 0; i < str.length; i++ ) {
        crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF];
    }

    return (crc ^ (-1)) >>> 0;
};

以下是性能差异的链接: http://jsperf.com/js-crc32

Here's a link to the performance difference: http://jsperf.com/js-crc32

这是我对此的反对意见。我认为读取一个数组的速度比对其进行分解要快。

Well here's my ameatur shot at this. I figured reading off an array is faster than substringing it.

警告但是,我在这些例子中使用了Utf8Encode函数来简化测试。毕竟,这些仅仅是一些例子而且很粗糙。

Warning though, I forwent the use of the Utf8Encode function in these examples to simplify the tests. After all, these are just examples and pretty rough ones at that.

这篇关于JavaScript CRC32的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆