Location>code7788 >text

0 and 1 are interchangeable, stop using three-point calculations

Popularity:284 ℃/2025-02-17 16:34:44

0 and 1 are often needed to be swapped in projects, especially switching states

For example: change to be released and removed, remove and re-list; turn on and disable, disable and open, etc.

The backend is often stored at a value of 0/1

At this time, you need to exchange 0 and 1

When you don't want to use a ternary expression (status === 0 ? 1 : 0)

3 simple methods can be used

1. ^ bitwise exclusive or

status^1 // When status is 1, output 0; when status is 0, output 1
1^1 // 0

0^1 // 1

2. ~Bitwise invert

Here you need to understand the data representation of the computer
The form of various numerical values ​​being represented in computers is called machine numbers. Its characteristic is that the binary count value is used, and the symbols of the number are represented by 0 and 1.Highest positionYesPositive and negativeNumberedSymbol bits, the rest represent numerical values

The machine length of modern computers is generally 8-bit integer times

  1. Original code: For example, the original code of 1 is 00000001
  2. Inverse code: The inverse code of a positive number is the same as the original code, while the inverse code of a negative number is the absolute value of the bit inverse code.
  3. Complement: The complement of a positive number is the same as its original and inverse codes, while the complement of a negative number is equal to the last bit of its inverse code plus 1
  4. Code shift: Add an offset to the number X

In computer systems, numerical values ​​are represented and stored in complement codes

~Bitwise inverse operator: Inverse each binary bit of the data, that is, turn 0 into 1 and 1 into 0

Please ~1

The binary of 1 is 00000001

Inverted to 111111110

The method to find the original code for complement is: add 1 inversely

111111110 Invert to 00000001 and add 1 to 00000010

And this value is a negative number, so the value of ~1 is -2

Please ~0

Similarly, the binary of 0 is 00000000

Invert it is 11111111. Find the original code first to get the invert code 000000000 and then add 1 to get 00000001

And this value is a negative number, so the value of ~0 is -1

~status+2 // When status is 1, output 0; when status is 0, output 1
~0+2 // 1

~1+2 // 0

3. <<shift operator

<<Access rules: move all numbers to the left in binary form and the corresponding number of digits, move the high position out (discard), and fill the zero position in the low position.

(1-n) << n

Calculate 1 - 1 << 1

The binary of 0 is 000000000. Move 1 bit to the left to 00000000, and the result is 0

Calculate 1 - 0 << 0

The binary of 1 is 00000001. The 0 bits are shifted to the right and 0 bits are 00000001, and the result is 1

1-status << status // When status is 1, output 0; when status is 0, output 1
(1-1) << 1  // 0
(1-0) << 0 //  1