Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
612 views
in Technique[技术] by (71.8m points)

jquery - Understanding bitwise operations in javascript

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>

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.

My question is either:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...