了解在JavaScript位操作 [英] Understanding bitwise operations in javascript

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

问题描述

我目前的XML文档内存储数据的二进制,20位长,各重presenting一个布尔值。

I am currently storing data inside an XML doc as binary, 20 digits long, each representing a boolean value.

<matrix> 

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

</matrix>

我用jQuery解析此,我目前使用的是循环和的charAt()来确定是否做的东西如果该值为==1。

I am parsing this with jQuery and am currently using a for loop and charAt() to determine whether to do stuff if the value is == "1".

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

这发生几次因为已经耗尽那种缓慢的一个巨大的循环的一部分。有人告诉我,我应该使用按位运算符来处理这一点,它会运行得更快。

This takes place a few times as part of a HUGE loop that has run sort of slow. Someone told me that I should use bitwise operators to process this and it would run faster.

有人可以给我的,我怎么能做到这一点的例子吗?我试图在线阅读教程和他们似乎是正确的飞在我的头上。 (FYI:我计划建立一个Ruby脚本,将转换二进制我0放大器1的进我的XML位)

Can someone offer me an example of how I could do this? I've tried to read tutorials online and they seem to be flying right over my head. (FYI: I am planning on creating a Ruby script that will convert my binary 0 & 1's into bits in my XML.)

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

Or does anyone know of a good, simple (maybe even dumbed down version) tutorial or something that could help me grasp these bitwise operator concepts?

推荐答案

假设你有不超过32位,您可以使用JavaScript的内置 parseInt函数()功能你的1和0的字符串转换为整数,然后用&放大器测试标志; (和)运算符:

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
}

...

另请参阅:如何检查我的字节标志

(问题是关于C中的使用,但适用于JS,以及同运营商)

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)

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

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