javascript - 位运算的意义何在(Espruino)

标签 javascript bit-manipulation

这行代码的含义是什么

n = (n<<1) | ((d>=0.0004)?1:0);

尝试理解函数 sigOff() 中的代码 http://www.espruino.com/Remote+Control+Sockets

最佳答案

此片段似乎使用 bitwise OR ( | ) 和左移 ( << ) 运算符:

Bitwise OR: a | b;
Returns a one in each bit position for which the corresponding bits of either or both operands are ones.
Left shift: a << b;
Shifts a in binary representation b (< 32) bits to the left, shifting in zeros from the right.

左移1 ( << 1 ) 基本上是 n 的值的两倍.
然后, or ( | ) 基本上“添加” 1到结果使其不均匀,如果 d >= 0.0004 .
如果d < 0.0004 ,左移的结果不变。

所以,对于 n == 3d == 0.0004 ,发生这种情况:

n << 1          // 6
(d>=0.0004)?1:0 // 1
6 | 1           // 7

对于n == 5d == 0.0002 ,发生这种情况:

n << 1          // 10
(d>=0.0004)?1:0 // 0
10 | 0          // 10

关于javascript - 位运算的意义何在(Espruino),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24239001/

相关文章:

c - 位集隶属函数

java - 为按位运算声明掩码

javascript - 具有半透明背景的堆叠模态显示具有更亮 Angular 落的异常背景

javascript - Bootstrap - 无法让我的 Accordion 在默认情况下保持关闭状态?

javascript - 使用 ExtJS 4 进行堆叠和分组图表

javascript - 未捕获( promise )TypeError : Already read

javascript - 多条件属性选择器

c - 结构分隔变量

arduino - 加速度计代码中的位移操作

java - 打印不带填充的 BinaryString