Note that all bitwise operations operate on 32-bit integers by passing any operands to the internal function ToInt32.
var a;
a = 0b0011 | 0b1010; // a === 0b1011
// truth table
// 1010 | (or)
// 0011
// 1011 (result)
a = 0b0011 & 0b1010; // a === 0b0010
// truth table
// 1010 & (and)
// 0011
// 0010 (result)
a = ~0b0011; // a === 0b1100
// truth table
// 10 ~(not)
// 01 (result)
a = 0b1010 ^ 0b0011; // a === 0b1001
// truth table
// 1010 ^ (xor)
// 0011
// 1001 (result)
a = 0b0001 << 1; // a === 0b0010
a = 0b0001 << 2; // a === 0b0100
a = 0b0001 << 3; // a === 0b1000
Shift left is equivalent to integer multiply by Math.pow(2, n)
. When doing integer math, shift can significantly improve the speed of some math operations.
var n = 2;
var a = 5.4;
var result = (a << n) === Math.floor(a) * Math.pow(2,n);
// result is true
a = 5.4 << n; // 20
>>
(Sign-propagating shift) >>>
(Zero-fill right shift)a = 0b1001 >> 1; // a === 0b0100
a = 0b1001 >> 2; // a === 0b0010
a = 0b1001 >> 3; // a === 0b0001
a = 0b1001 >>> 1; // a === 0b0100
a = 0b1001 >>> 2; // a === 0b0010
a = 0b1001 >>> 3; // a === 0b0001
A negative 32bit value always has the left most bit on:
a = 0b11111111111111111111111111110111 | 0;
console.log(a); // -9
b = a >> 2; // leftmost bit is shifted 1 to the right then new left most bit is set to on (1)
console.log(b); // -3
b = a >>> 2; // leftmost bit is shifted 1 to the right. the new left most bit is set to off (0)
console.log(b); // 2147483643
The result of a >>>
operation is always positive.
The result of a >>
is always the same sign as the shifted value.
Right shift on positive numbers is the equivalent of dividing by the Math.pow(2,n)
and flooring the result: