define

Bitwise operations perform calculations on binary numbers, bitwise operations on integers.

For example, 1+1=2, which is correct in decimal computation, but 1+1=10 in binary computation; If you take the binary number 100 backwards, it’s 001 instead of -100.

classification

There are seven bitwise operators, divided into two categories:

  • Logical bit operators:Bit and (&),Or (|),Bit other or (^),Not bit (~)
  • Shift operator:Shift left (<<),Move right (>>),Unsigned right shift (>>>)

&The operator

The & operator (bitwise and) is used to compare two binary operands bitwise and return the result according to the conversion table shown in the following table.

&The operator
1 1 1
1 0 0
0 1 0
0 0 0

In bit operations, the value 1 means true, 0 means false, and vice versa.

The bitwise and operation of 12 and 5 returns 4.

console.log(12 & 5) / / 4
Copy the code

|The operator

“|” operator (or) is used to compare two binary operand bit by bit, according to the conversion table of as shown in the table and returns the result.

|The operator
1 1 1
1 0 1
0 1 1
0 0 0

The bitwise or operation on 12 and 5 returns 13.

console.log(12 | 5) / / 13
Copy the code

^The operator

The “^” operator (bitwise xor) is used to compare two binary operands bit by bit and returns the result according to a conversion table as shown in the table.

^The operator
1 1 0
1 0 1
0 1 1
0 0 0

The bit xor operation on 12 and 5 returns 9.

console.log(12 ^ 5) / / 9
Copy the code

~The operator

The “~” operator (bitwise not) is used to negate a binary operand bit by bit.

  1. Converts an operand to a 32-bit binary integer.
  2. Bit – by – bit operation.
  3. Converts binary inverse code to decimal floating-point number.
console.log( ~12 ) / / - 13
Copy the code

Bitwise nonoperation is essentially taking the negative of a number and subtracting it by 1.

console.log( ~ 12= =12-1) // true
Copy the code