The number type of JavaScript is a double-precision IEEE 754 64-bit floating-point type, but in bitwise operations, bitwise operators are applied to 32-bit numbers, and any numeric operation is converted to 32 bits, and the result is then converted to a Js number type.
All operands of bitwise operators are converted to two's complement signed 32-bit integers. Conceptually, bitwise logical operators follow the following rules:
0 and 1), with digits beyond 32 bits being discarded.For each bit, the result is 1 only if both corresponding bits of the two operands are 1; otherwise, it's 0. The truth table is as follows:
| a | b | a & b |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 1 | 1 | 1 |
We can use the & operator to determine the parity of a number.
For each bit, the result is 1 if at least one of the corresponding bits of the two operands is 1; otherwise, it's 0. The truth table is as follows:
| a | b | a | b |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 1 |
We can use the | operator to force the value to be an int 32 or a 32-bit integer type.
For each bit, the result is 1 only if one and only one of the corresponding bits of the two operands is 1; otherwise, it's 0. The truth table is as follows:
| a | b | a ^ b |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
We can use the ^ operator to swap numbers.
It can also be used to determine whether the signs of values are the same.
For each bit, the bit is inverted, i.e., 0 becomes 1 and 1 becomes 0. The truth table is as follows:
| a | ~ a |
|---|---|
| 0 | 1 |
| 1 | 0 |
We can use the ~ operator to force the value to be an int 32 or a 32-bit integer type.
Shifts the binary representation of a value to the left by n (n < 32) bits, filling the right with 0.
We can use the << operator to perform integer * 2^n operations.
We can use the << operator to force the value to be an int 32 or a 32-bit integer type.
Shifts the binary representation of a value to the right by n (n < 32) bits, discarding the bits that are shifted out.
We can use the << operator to perform integer / 2^n operations.
We can use the >> operator to force the value to be an int 32 or a 32-bit integer type.
Shifts the binary representation of a value to the right by n (n< 32) bits, discarding the bits that are shifted out, and fills the left with 0. Therefore, the result is always non-negative, even if zero bits are shifted to the right, so >>> is generally not used for negative number operations.
We can use the << operator to perform integer / 2^n operations, noting that it is not used for negative number operations.
We can use the >> operator to force the value into a 32-bit integer, which is 32, note that it is not used for negative number operations.