Binary operator

Overview

Binary bit operators are used to directly calculate binary bits, there are 7 in total.

-Binary OR operator (or): The symbol is |, which means that if both binary bits are 0, the result is 0, otherwise it is 1. -Binary AND Operator (and): The symbol is &, which means that if both binary bits are 1, the result is 1, otherwise it is 0. -Binary negation operator (not): The symbol is ~, which means to invert a binary bit. -Exclusive OR operator (xor): The symbol is ^, which means that if the two binary bits are not the same, the result is 1, otherwise it is 0. -Left shift operator (left shift): The symbol is <<, see the explanation below for details. -Right shift operator (right shift): The symbol is >>, see the explanation below for details. -** Zero filled right shift operator ** (zero filled right shift): The symbol is >>>, see the explanation below for details.

These bit operators directly deal with each bit (bit), so they are very low-level operations. The advantage is that they are extremely fast, but the disadvantage is that they are very unintuitive. They cannot be used in many situations, otherwise the code will be difficult to understand and error-checking.

One thing to pay special attention to is that bitwise operators only work on integers. If an operator is not an integer, it will be automatically converted to an integer and then executed. In addition, although in JavaScript, values ​​are stored in the form of 64-bit floating-point numbers, when doing bitwise operations, they are calculated as 32-bit signed integers, and the return value is also a 32-bit signed integer.

i = i | 0;

The meaning of the above line of code is to convert i (whether it is an integer or a decimal) to a 32-bit integer.

Using this feature, you can write a function to convert any value to a 32-bit integer.

function toInt32(x) {
  return x | 0;
}
```The

above function will OR any value with `0` once. This bitwise operation will automatically convert a value to a 32-bit integer. The following is the usage of this function.

```javascript
toInt32(1.001) // 1
toInt32(1.999) // 1
toInt32(1) // 1
toInt32(-1) // -1
toInt32(Math.pow(2, 32) + 1) // 1
toInt32(Math.pow(2, 32)-1) // -1
```In the

above code, `toInt32` can convert decimals to integers. For general integers, there will be no change in the return value. For integers greater than or equal to the 32nd power of 2, digits greater than 32 bits will be rounded off.

## Binary OR Operator The

binary OR operator (`|`) compares two operators bit by bit. As long as one of the two binary bits is `1`, it returns `1`, otherwise it returns `0`.

```javascript
0 | 3 // 3
```In the

above code, the binary forms of `0` and `3` are `00` and `11` respectively, so performing a binary OR operation will get `11` (that is, ` 3`).

Bit arithmetic is only valid for integers. When a decimal is encountered, the decimal part will be discarded and only the integer part will be retained. Therefore, performing a binary OR operation between a decimal number and `0` is equivalent to removing the decimal part of the number, that is, taking the integer digits.

```javascript
2.9 | 0 // 2
-2.9 | 0 // -2
```It

should be noted that this rounding method does not apply to numbers that exceed the 32-bit integer maximum value `2147483647`.

```javascript
2147483649.4 | 0;
// -2147483647

Binary AND Operator

The rule of binary AND operator (&) is to compare two operators bit by bit, and only one of the two binary bits If the bit is 0, return 0, otherwise return 1.

0 & 3 // 0
```In the

above code, the binary AND operation of 0 (binary `00`) and 3 (binary `11`) will get `00` (ie `0`).

## Binary negation operator The

binary negation operator (`~`) changes each binary bit to the opposite value (`0` becomes `1`, and `1` becomes `0`). Its return results are sometimes difficult to understand, because it involves the internal numerical representation mechanism of the computer.

```javascript
~ 3 // -4
```The

above expression performs the binary negation of `3` to get `-4`. The reason for this result is that JavaScript internally converts all operators into 32-bit binary integers for bitwise operations.

The 32-bit integer form of `3` is `00000000000000000000000000000011`, after the binary negation operation, the result is `11111111111111111111111111111100`. Since the first bit (sign bit) is 1, this number is a negative number. JavaScript uses the complement form to represent negative numbers, that is, you need to subtract 1 from this number, take the inverse again, and add the negative sign to get the decimal value corresponding to the negative number. This number minus 1 is equal to `11111111111111111111111111111011`, and then inverted again to get `00000000000000000000000000000100`, plus the minus sign is `-4`. Considering that such a process is troublesome, it can be simply memorized as a number plus its own negated value, which is equal to -1.

```javascript
~ -3 // 2
```The

above expression can be calculated like this, the negated value of `-3` is equal to `-1` minus `-3`, and the result is `2`.

Perform two consecutive binary negation operations on an integer to get itself.

```javascript
~~3 // 3

All bit operations are only valid for integers. When the binary negation operation encounters a decimal, the decimal part will be discarded, and only the integer part will be retained. Therefore, two consecutive binary negation operations on a decimal number can achieve the effect of rounding.

~~2.9; // 2
~~47.11; // 47
~~1.9999; // 1
~~3; // 3

Rounding using binary negation is the fastest of all rounding methods.

Perform a binary negation operation on a string, and the JavaScript engine will first call the Number function to convert the string to a numeric value.

// equivalent to ~Number('011')
~'011' // -12

// equivalent to ~Number('42 cats')
~'42 cats' // -1

// equivalent to ~Number ('0xcafebabe')
~'0xcafebabe' // 889275713

// equivalent to ~Number('deadbeef')
~'deadbeef'
// -1 ``` The

`Number` function converts a string to a numeric value, see the chapter "Data Type Conversion".

For other types of values, the binary negation operation is first converted to a number with `Number`, and then processed.

```javascript
// equivalent to ~Number([])
~[] // -1

// equivalent to ~Number(NaN)
~NaN // -1

// equivalent to ~Number(null)
~null //- 1

XOR operator The

XOR operation (^) returns 1 when the two binary digits are different, and returns 0 when they are the same.

0 ^ 3; // 3

In the above expression, 0 (binary 00) and 3 (binary 11) are XORed, and their binary bits are different, so 11 (ie 3) is obtained.

There is a special application of "exclusive OR", which is to perform exclusive OR operation on two numbers a and b three times in succession, a^=b; b^=a; a^=b;, can be interchangeable their values. This means that the "exclusive OR operation" can exchange the values ​​of two variables without introducing temporary variables.

var a = 10;
var b = 99;

(a ^= b), (b ^= a), (a ^= b);

a; // 99
b; // 10

This is to swap the values ​​of two variables The fastest way.

The exclusive OR operation can also be used for rounding.

12.9 ^ 0; // 12

Left shift operator The

left shift operator (<<) means to move the binary value of a number to the left by a specified number of bits, with 0 at the end, That is, multiplied by the specified power of 2. When moving to the left, the sign bit of the highest bit is moved together.

// The binary form of 4 is 100,
// shifting one bit to the left is 1000 (that is, 8 in decimal)
// equivalent to multiplying by 2 to the power of
4 << 1
// 8

-4 << 1
// -8
```In the

above code, `-4` is shifted by one bit to the left to get `-8`, because the binary form of `-4` is `11111111111111111111111111111100`, and after shifting by one bit to the left, `11111111111111111111111111111000` is obtained, which is converted to decimal (Subtract 1 and take the inverse, plus the minus sign) is `-8`.

If it is shifted by 0 bits to the left, it is equivalent to converting the value to a 32-bit integer, which is equivalent to rounding, and it is valid for both positive and negative numbers.

```javascript
13.5 << 0
// 13

-13.5 << 0
// -13
```The

left shift operator is very convenient for binary values.

```javascript
var color = (r: 186, g: 218, b: 85);

// RGB to HEX
// The function of (1 << 24) is to ensure that the result is 6 digits
var rgb2hex = function(r, g, b) {
  return'#' + ((1 << 24) + (r << 16) + (g << 8) + b)
    .toString(16) // first convert to hexadecimal, then Return the
    string.substr(1); // Remove the highest bit of the string and return the next six strings
}

rgb2hex(color.r, color.g, color.b)
// "#bada55"

The above code uses the left shift operator to convert the RGB value of the color into a HEX value.

## Right shift operator The

right shift operator (`>>`) means to move the binary value of a number to the right by a specified number of digits. If it is a positive number, the head is filled with `0`; if it is negative, the head is filled with `1`. The right shift operator is basically equivalent to dividing by the specified power of `2` (the highest bit is the sign bit participating in the shift).

```javascript
4 >> 1
// 2
/*
// Because the binary form of 4 is 00000000000000000000000000000100,
// shift one bit to the right to get 00000000000000000000000000000010,
// which is 2 in decimal
*/

-4 >> 1
// -2
/*
// Because the binary form of -4 is 11111111111111111111111111111111100,
// shift one bit to the right and add 1 to the head to get 11111111111111111111111111111110,
// which is -2 in decimal
*/
```The

right shift operation can simulate the division of 2 .

```javascript
5 >> 1
// 2
// equivalent to 5/2 = 2

21 >> 2
// 5
// equivalent to 21/4 = 5

21 >> 3
// 2
// equivalent to 21/8 = 2

21 >> 4
// 1
// equivalent to 21/16 = 1

Right shift operator with zero padding at the head, zero padding at the

head The only difference between the right shift operator (>>>) and the right shift operator (>>) is that when the binary form of a number moves to the right, the head will always be filled with zeros, regardless of the sign bit. Therefore, this operation always results in a positive value. For positive numbers, the result of this operation is exactly the same as the right shift operator (>>), the difference lies mainly in negative numbers.

(4 >>>
  (1 -
    // 2

    4)) >>>
  1;
// 2147483646
/* 
// Because the binary form of -4 is 11111111111111111111111111111100, 
// the signed bit is shifted one bit to the right to get 01111111111111111111111111111110, 
// It is 2147483646 in decimal. 
*/

This operation actually converts a value into a 32-bit unsigned integer.

The fastest way to view the storage form of a negative integer in the computer is to use this operator.

-1 >>> 0; // 4294967295

The code above indicates that when -1 is used as a 32-bit integer, the internal storage format is interpreted using unsigned integer format, and the value is 4294967295 (ie (2^32)-1, which is equal to 11111111111111111111111111111).

Switch function

Bit operators can be used as switches for setting object properties.

Suppose an object has four switches, and each switch is a variable. Then, you can set a four-digit binary number, each of which corresponds to a switch.

var FLAG_A = 1; // 0001
var FLAG_B = 2; // 0010
var FLAG_C = 4; // 0100
var FLAG_D = 8; // 1000
```The

above code sets A, B, C, D four Each switch occupies a binary bit.

Then, you can use the binary AND operation to check whether the specified switch is turned on in the current setting.

```javascript
var flags = 5; // Binary 0101

if (flags & FLAG_C) {
  // ...
}
// 0101 & 0100 => 0100 => true
```The

above code checks whether the switch is turned on`C `. If it is turned on, it will return `true`, otherwise it will return `false`.

Now suppose we need to turn on the three switches `A`, `B`, and `D`, we can construct a mask variable.

```javascript
var mask = FLAG_A | FLAG_B | FLAG_D;
// 0001 | 0010 | 1000 => 1011
```The

above code performs a binary OR operation on the three variables `A`, `B`, and `D`, and the mask value is binary The `1011`.

With the mask, the binary OR operation can ensure that the specified switch is turned on.

```javascript
flags = flags | mask;
```In the

above code, the `flags` variable obtained after calculation represents that the binary bits of the three switches are all turned on.

Binary AND operation can close all the items that are different from the switch settings in the current settings.

```javascript
flags = flags & mask;
```The

XOR operation can toggle the current setting, that is, the opposite value of the current setting can be obtained the first time it is executed, and the original value can be obtained again by executing it again.

```javascript
flags = flags ^ mask;
```The

binary negation operation can flip the current setting, that is, the original setting is `0`, and it becomes `1` after the operation; the original setting is `1`, and it becomes `0 after the operation. `.

```javascript
flags = ~flags;