Logical bit operators
Logical operators: and (&), or (|), an exclusive or (^), a (~)
In bit operations, the value 1 means true, 0 means false, and vice versa
And (&)
If both bits are 1, the result is 1, otherwise the result is 0
let a = 5; // 00000000000000000000000000000101
a &= 3; // 00000000000000000000000000000011
console.log(a); // 00000000000000000000000000000001
// expected output: 1
Copy the code
Bit or (|)
As long as one bit of any expression is 1, that bit in the result is 1. Otherwise, the bit in the result is 0
let a = 5; // 00000000000000000000000000000101
a |= 3; // 00000000000000000000000000000011
console.log(a); // 00000000000000000000000000000111
// expected output: 7
Copy the code
An exclusive or (^)
The result is 0 if the two operands are the same, 1 otherwise
let a = 5; // 00000000000000000000000000000101
a ^= 3; // 00000000000000000000000000000011
console.log(a); // 00000000000000000000000000000110
// expected output: 6
Copy the code
Not (~)
The reverse bitwise operation reverses each of its bits. 0 becomes 1,1 becomes 0
const a = 5; // 00000000000000000000000000000101
const b = -3; // 11111111111111111111111111111101
console.log(~a); // 11111111111111111111111111111010
// expected output: -6
console.log(~b); // 00000000000000000000000000000010
// expected output: 2
Copy the code
Shift operator
Shift operators :(<<, >> and >>>)
> > =
let a = 5; // 00000000000000000000000000000101
a >>= 2; // 00000000000000000000000000000001
console.log(a);
// expected output: 1
Copy the code
< < =
let a = 5; // 00000000000000000000000000000101
a <<= 2; // 00000000000000000000000000010100
console.log(a);
// expected output: 20
Copy the code
>>>
Operator performs an unsigned right shift operation
A positive number
For an unsigned or positive right shift operation, the result of an unsigned right shift is the same as that of a signed right shift operation.
const a = 5; // 00000000000000000000000000000101
const b = 2; // 00000000000000000000000000000010
console.log(a >> b); // 00000000000000000000000000000001
console.log(a >>> b); // 00000000000000000000000000000001
// expected output: 1
Copy the code
A negative number
For negative numbers, an unsigned right shift fills all vacancies with 0 and treats negative numbers as positive numbers
console.log(-1000 >> 8); // Return value -4 console.log(-1000 >>> 8); // Returns the value 16777212Copy the code
reference
C.biancheng.net/view/5471.h…
www.taichi-maker.com/homepage/re…
other
Bit operations add and subtract numbers