4

我目前将数据以二进制形式存储在 XML 文档中,长度为 20 位,每个代表一个布尔值。

<matrix> 

    <resource type="single"> 
        <map>10001010100011110000</map> 
        <name>Resource Title</name> 
        <url>http://www.yoursite.com</url> 
    </resource>

</matrix>

我正在用 jQuery 解析它,并且目前正在使用一个for循环charAt()来确定如果值是 ==“1”是否要执行一些操作。

for (var i = 0; i < _mapLength; i++) {
    if (map.charAt(i) == "1") {
        //perform something here
    }
}

作为运行缓慢的巨大循环的一部分,这发生了几次。有人告诉我,我应该使用按位运算符来处理它,它会运行得更快。

我的问题是:

有人可以给我一个例子来说明我如何做到这一点吗? 我试图在网上阅读教程,它们似乎就在我的头上飞过。(仅供参考:我计划创建一个 Ruby 脚本,将我的二进制 0 和 1 转换为我的 XML 中的位。)

或者有没有人知道一个好的、简单的(甚至可能是简化版)教程或可以帮助我掌握这些按位运算符概念的东西?

4

4 回答 4

14

Assuming you have no more than 32 bits, you can use JavaScript's built-in parseInt() function to convert your string of 1s and 0s into an integer, and then test the flags using the & (and) operator:

var flags = parseInt("10001010100011110000", 2); // base 2

if ( flags & 0x1 )
{
   // do something
}

...

See also: How to check my byte flag?

(question is on the use in C, but applies to the same operators in JS as well)

于 2009-06-16T21:06:42.707 回答
3

Single ampersand (&, as opposed to &&) does bit-wise comparison. But first you need to convert your strings to numbers using parseInt().

var map = parseInt("10010", 2); // the 2 tells it to treat the string as binary

var maskForOperation1 = parseInt("10000", 2);
var maskForOperation2 = parseInt("01000", 2);
// ...

if (map & maskForOperation1) { Operation1(); }
if (map & maskForOperation2) { Operation2(); }
// ...
于 2009-06-16T21:09:47.320 回答
3

要格外小心。Javascript 没有整数——数字存储为 64 位浮点数。您应该可以准确地转换为 52 位。如果你得到的标志比这更多,那么当你的“数字”四舍五入到最接近的可表示浮点数时,就会发生不好的事情。(哎哟!)

此外,按位操作对性能没有帮助,因为浮点数将被转换为整数,经过测试,然后再转换回来。

如果您有几个要检查标志的地方,我会在一个对象上设置标志,最好带有名称,如下所示:

var flags = {};
flags.use_apples = map.charAt(4);
flags.use_bananas = map.charAt(10);

ETC...

然后你可以在你的循环中测试这些标志:

if(flags.use_apples) {
    do_apple_thing();
}

对象槽测试将比按位检查更快,因为 Javascript 未针对按位运算符进行优化。但是,如果您的循环很慢,我担心解码这些标志可能不是缓慢的根源。

于 2009-06-29T19:19:30.107 回答
1

Bitwise operators will certainly be faster but only linearly and not by much. You'll probably save a few milliseconds (unless you're processing HUGE amounts of data in Javascript, which is most likely a bad idea anyway).

You should think about profiling other code in your loop to see what's slowing it down the most. What other algorithms, data structures and allocations do you have in there that could use refactoring?

于 2009-06-16T21:09:04.763 回答