Understanding bitwise operations in javascript(理解 javascript 中的按位运算)
问题描述
我目前将数据以二进制形式存储在 XML 文档中,长度为 20 位,每个代表一个布尔值.
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 解析它,目前正在使用 for
循环和 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.
谁能给我举个例子来说明我是如何做到这一点的?我试过在线阅读教程,它们似乎就在我头顶上.(仅供参考:我正计划创建一个 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.)
或者有谁知道一个好的、简单的(甚至可能是简化版)教程或可以帮助我掌握这些按位运算符概念的东西?
推荐答案
假设你的位数不超过 32 位,你可以使用 JavaScript 内置的 parseInt()
函数来转换你的 1 字符串和 0 转换为整数,然后使用 &
(and) 运算符测试标志:
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 中的相同运算符)
Seealso:Howtocheckmybyteflag?
(question is on the use in C, but applies to the same operators in JS as well)
这篇关于理解 javascript 中的按位运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!