About
See en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators
Bitwise binary operator may also be used as assignment operator
Articles Related
Type
- the bitwise arithmetic operators (~, &, ^, and |)
- and the shift operators (<<, >>, and >>>).
Arithmetic
The bitwise arithmetic operators
- ~ (NOT)
- & (AND)
- ^ (XOR)
- and | OR
They are also Boolean operator.
NOT (~)
- ~, the Bitwise NOT Operator
// ~x is roughly the same as -(x+1)
console.log(~2); // -(2+1) ==> -3
XOR (^) - Exclusive OR
The bitwise addition, modulo 2, of two bit strings of equal length.
The bitwise XOR expression follows the following rules:
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0
Example
console.log(6 ^ 2); // 110 ^ 010 = 100 = 4
OR (|)
The bitwise OR expression follows the following rules:
0 | 0 = 0
0 | 1 = 1
1 | 0 = 1
1 | 1 = 1
Example:
console.log(6 | 2); // 110 ^ 010 = 110 = 6
console.log(8 | 1); // 1000 ^ 0001 = 1001 = 9
AND (&)
0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1
Shift
The shift operators shifts the digits to the left or to the right:
- moving the bits to the left or to the right (if you need to position them inside a fix number of bit)
- and/or multiplying or dividing by 2
List:
- << - shift to the left (ie multiply by 2)
- >> - shift to the right (divide by 2)
- and >>>
Example / Demo:
- The initial value of 1 in bit
const foo = '0001'; // 1
console.log(`Initial Value: bit: ${foo}, decimal ${parseInt(foo, 2)}`);
- Shift one bit to the left (multiply by 2)
let fooShifted = parseInt(foo, 2) << 1
console.log(`shifted by one (x2): bit: ${fooShifted.toString(2)}, decimal: ${fooShifted}`);
- Shift two bit to the left (2×2)
fooShifted = parseInt(foo, 2) << 2
console.log(`shifted by two (x2 x2): bit: ${fooShifted.toString(2)}, decimal: ${fooShifted}`);