And (with) | & |
Or(或) | | |
Exclusive Or(异或) |
^ |
Not (not) | ~ |
Now the answer comes, because ' & ' is already taken and is a bitwise operator
Here we do not discuss the principle of bitwise operators, if you are interested, you can Google it yourself
Not ~
Not essentially rounds down the number and subtracts 1
var num = 20.1
console.log(~num) // -21
And &
This is a little more complicated
Operates on the binary form of a number. It aligns the digits in each number and then ANDs the two digits in the same position using the following rules:
digits in the first digit | digits in the second digit | result |
1 | 1 | 1 |
1 | 0 | 0 |
0 | 1 | 0 |
0 | 0 | 0 |
Example: 30 & 3
Let's first look at the binary of the two numbers
var i = 30
i.toString(2) // 11110
var j = 3
j.toString(2) // 11
console.log(i & j) // 2
Why '2'?
Let's take a look. According to the relationship in the above table, we can get the results in the following table
30 | 1 1110 |
3 | 0 0011 |
result | 0 0010 |
The decimal number corresponding to '10' in binary is '2'
Or |
or is similar to and is also calculated after converting to binary, but the rules are different
Digits in the first digit | the number of digits in the second digit | result |
1 | 1 | 1 |
1 | 0 | 1 |
0 | 1 | 1 |
0 | 0 | 0 |
Similarly, let's take 30 | 3 as an example
var i = 30
i.toString(2) // 11110
var j = 3
j.toString(2) // 11
console.log(i | j) // 31
30 | 1 1110 |
3 | 0 0011 |
result | 1 1111 |
Exclusive Or ^ (or Xor)
Also similar to or and and but with different rules
Digits in the first digit | digits in second digit | result |
1 | 1 | 0 |
1 | 0 | 1 |
0 | 1 | 1 |
0 | 0 | 0 |
var i = 30
i.toString(2) // 11110
var j = 3
j.toString(2) // 11
console.log(i ^ j) // 29
30 | 1 1110 |
3 | 0 0011 |
result | 1 1101 |
Then after reading these 4 basic operations,
Where is our magic trick?
Let's go back to the Not operator. It can be said that the three bit operations of And Or Xor are less likely to be used.
But the rule of Not is to round down and subtract 1 from the negative
Pay attention to the keywords I highlighted. Did something come to mind? That's right Math.floor()
If a single use of Not is a negative minus 1, what will happen if I use Not twice in a row? Twice in a row is itself for integer numbers, but what about floating point numbers? Isn't that his rounding down?
To verify we can try
var i = 25.1
console.log(~~i) //25
But some people say that there is a Math.floor() method for rounding down?
Okay, that's what we're doing, why use Not twice instead of Math.floor()
First, don't you think '~~' is faster to type than 'Math.floor()'?
Second, '~~' is faster than 'Math.floor()'.
Math.floor() runs at 3.5 millions ops/sec