Home  >  Article  >  Web Front-end  >  Let’s talk about the 7 kinds of bit operators in JavaScript and see how they are used in actual combat?

Let’s talk about the 7 kinds of bit operators in JavaScript and see how they are used in actual combat?

青灯夜游
青灯夜游forward
2022-01-06 10:46:372721browse

This article will take you through the 7 kinds of bit operators in JavaScript and see how to use these 7 kinds of bit operators. I hope it will be helpful to you!

Let’s talk about the 7 kinds of bit operators in JavaScript and see how they are used in actual combat?

Bit operators

Operators are used for the underlying operations of numerical values, that is, to operate the data represented in the memory. bit (bit).

ECMAScript All values ​​in ECMAScript

are stored in IEEE 754 64-bit format, but bit operations are not directly applied to the 64-bit representation, but the value is first converted to 32-bit integer, perform bit operations, and then convert the result to 64 bits.

To the developer, it is as if there are only 32-bit integers, because the 64-bit integer storage format is invisible. Now that we know this, we only need to consider 32-bit integers.

Signed integer uses the first 31 bits of 32 bits to represent the integer value. Bit 32 represents the sign of the value, such as 0 indicating positive and 1 indicating negative. This bit is called the sign bit, and its value determines the format of the rest of the value. Positive values ​​are stored in true binary format, i.e. each of the 31 bits represents a power of 2. The first bit (called bit 0) represents 20 , the second bit represents 21 , and so on.

If a bit is empty, it is filled with 0, which is equivalent to ignoring it. For example, the binary format of the value 18 is 0000000000000000000000000010010, or more compactly 10010. The latter are the 5 valid bits used to determine the actual value (as shown in the figure below).

Let’s talk about the 7 kinds of bit operators in JavaScript and see how they are used in actual combat?

Bitwise NOT~

Bitwise NOT operator uses tilde The symbol (~) indicates that its function is to return the one's complement of the value. Bitwise NOT is one of the few binary math operators in ECMAScript. Look at the following example:

let num1 = 25; //二进制 00000000000000000000000000011001
let num2 = ~num1; // 二进制 11111111111111111111111111100110
console.log(num2); // -26

Here, the bitwise NOT operator is applied to the value 25, and the result is 26. It can be seen that the final effect of bitwise not is to invert the value and subtract 1, just like the result of performing the following operation:

let num1 = 25;
let num2 = -num1 - 1;
console.log(num2); // "-26"

In fact, although the results returned by the two are the same, the bit The speed of operation is much faster. This is because bit operations are performed on the underlying representation of the numeric value.

Bitwise AND&

The bitwise AND operator is represented by the ampersand (&), there are two Operands. Essentially, bitwise AND is to align each bit of two numbers, and then perform the corresponding AND operation on each bit based on the rules in the truth table.

Let’s talk about the 7 kinds of bit operators in JavaScript and see how they are used in actual combat?

The bitwise AND operation returns 1 when both bits are 1 and returns 0 when either bit is 0. Let's look at an example where we do the AND operation on the values ​​25 and 3, as shown below:

let result = 25 & 3;
console.log(result); // 1 25 和 3 的按位与操作的结果是 1。

Why? Look at the following binary calculation process:

Let’s talk about the 7 kinds of bit operators in JavaScript and see how they are used in actual combat?

As shown in the figure above, in the binary representation of 25 and 3, only the two numbers in the 0th bit are 1. All other bits of the result value are then filled with 0s, so the result is 1.

Bitwise OR

##The bitwise OR operator is represented by the pipe symbol (|), and there are also two operands. Bitwise OR follows the following truth table:

Let’s talk about the 7 kinds of bit operators in JavaScript and see how they are used in actual combat?

##The bitwise OR operation returns 1 if at least one bit is 1 and returns 0 if both bits are 0. Still using the bitwise AND example, if you perform a bitwise OR on 25 and 3, the code is as follows:

let result = 25 | 3;
console.log(result); // 27

It can be seen that the result of the bitwise OR operation on 25 and 3 is 27:

Let’s talk about the 7 kinds of bit operators in JavaScript and see how they are used in actual combat?

In the two numbers involved in the calculation, 4 bits are all 1, so they directly correspond to the result. The binary code 11011 is equal to 27.

Bitwise XOR^

Bitwise XOR is represented by the caret (^), there are also two operands. The following is the truth table of bitwise XOR:

Let’s talk about the 7 kinds of bit operators in JavaScript and see how they are used in actual combat?

The difference between bitwise XOR and bitwise OR is that it only returns 1 when one bit is 1. (If both bits are 1 or 0, 0 is returned). Perform a bitwise XOR operation on the values ​​25 and 3:

let result = 25 ^ 3;
console.log(result); // 26

As you can see, the result of the bitwise XOR operation on 25 and 3 is 26, as follows:

Let’s talk about the 7 kinds of bit operators in JavaScript and see how they are used in actual combat?

两个数在 4 位上都是 1,但两个数的第 0 位都是 1,因此那一位在结果中就变成了 0。其余位上的 1 在另一个数上没有对应的 1,因此会直接传递到结果中。二进制码 11010 等于 26。(注意,这比对同样 两个值执行按位或操作得到的结果小 1。)

左移

左移操作符用两个小于号(

let oldValue = 2; // 等于二进制 10
let newValue = oldValue << 5; // 等于二进制 1000000,即十进制 64

注意在移位后,数值右端会空出 5 位。左移会以 0 填充这些空位,让结果是完整的 32 位数值(见下图)。

Let’s talk about the 7 kinds of bit operators in JavaScript and see how they are used in actual combat?

注意,左移会保留它所操作数值的符号。比如,如果-2 左移 5 位,将得到-64,而不是正 64。

有符号右移 >>

有符号右移由两个大于号(>>)表示,会将数值的所有 32 位都向右移,同时保留符号(正或负)。 有符号右移实际上是左移的逆运算。比如,如果将 64 右移 5 位,那就是 2:

let oldValue = 64; // 等于二进制 1000000
let newValue = oldValue >> 5; // 等于二进制 10,即十进制 2

同样,移位后就会出现空位。不过,右移后空位会出现在左侧,且在符号位之后(见图 3-3)。 ECMAScript 会用符号位的值来填充这些空位,以得到完整的数值。

Let’s talk about the 7 kinds of bit operators in JavaScript and see how they are used in actual combat?

无符号右移 >>>

无符号右移用 3 个大于号表示(>>>),会将数值的所有 32 位都向右移。对于正数,无符号右移与 有符号右移结果相同。仍然以前面有符号右移的例子为例,64 向右移动 5 位,会变成 2:

let oldValue = 64; // 等于二进制 1000000 
let newValue = oldValue >>> 5; // 等于二进制 10,即十进制 2

对于负数,有时候差异会非常大。与有符号右移不同,无符号右移会给空位补 0,而不管符号位是 什么。对正数来说,这跟有符号右移效果相同。但对负数来说,结果就差太多了。无符号右移操作符将负数的二进制表示当成正数的二进制表示来处理。因为负数是其绝对值的二补数,所以右移之后结果变 得非常之大,如下面的例子所示:

let oldValue = -64; // 等于二进制 11111111111111111111111111000000
let newValue = oldValue >>> 5; // 等于十进制 134217726

在对-64 无符号右移 5 位后,结果是 134 217 726。这是因为-64 的二进制表示是 1111111111111111111 1111111000000,无符号右移却将它当成正值,也就是 4 294 967 232。把这个值右移 5 位后,结果是 00000111111111111111111111111110,即 134 217 726。

实战中的妙用

1.判断奇偶数

// 偶数 & 1 = 0
// 奇数 & 1 = 1
console.log(2 & 1) // 0
console.log(3 & 1) // 1

2. 使用^来完成值的交换

let a = 2
let b = 5
a ^= b
b ^= a
a ^= b
console.log(a) // 5
console.log(b) // 2

3. 使用~进行判断

// 常用判断
if (arr.indexOf(item) > -1) {
    // code
}
// 按位非    ~-1 = -(-1) - 1 取反再 -1
if (~arr.indexOf(item)) {
    // code
}

4. 使用&>>|来完成rgb值和16进制颜色值之间的转换

/**
 * 16进制颜色值转RGB
 * @param  {String} hex 16进制颜色字符串
 * @return {String}     RGB颜色字符串
 */
  function hexToRGB(hex) {
    var hexx = hex.replace('#', '0x')
    var r = hexx >> 16
    var g = hexx >> 8 & 0xff
    var b = hexx & 0xff
    return `rgb(${r}, ${g}, ${b})`
}

/**
 * RGB颜色转16进制颜色
 * @param  {String} rgb RGB进制颜色字符串
 * @return {String}     16进制颜色字符串
 */
function RGBToHex(rgb) {
    var rgbArr = rgb.split(/[^\d]+/)
    var color = rgbArr[1]<<16 | rgbArr[2]<<8 | rgbArr[3]
    return '#'+ color.toString(16)
}
// -------------------------------------------------
hexToRGB('#ffffff')               // 'rgb(255,255,255)'
RGBToHex('rgb(255,255,255)')      // '#ffffff'

5. 使用|~>>>>>来取整

console.log(~~ 3.1415)    // 3
console.log(3.1415 >> 0)  // 3
console.log(3.1415 << 0)  // 3
console.log(3.1415 | 0)   // 3
// >>>不可对负数取整
console.log(3.1415 >>> 0)   // 3

【相关推荐:javascript学习教程

The above is the detailed content of Let’s talk about the 7 kinds of bit operators in JavaScript and see how they are used in actual combat?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete