JavaScript operator--Bitwise operator FULL Introduction _ Basics

Source: Internet
Author: User
Tags bitwise bitwise operators numeric numeric value switches

Front.

Bitwise operators are very low-level operations and are not commonly used because they are not intuitive. However, its speed is very fast, and reasonable use can achieve very good results. This article will introduce the operator-bitwise operator, which is often overlooked in JavaScript

Binary representation 

All values in the ECMAScript are stored in IEEE-754 64-bit format, but the bitwise operator does not manipulate 64-bit values directly, but rather with a 32-bit signed integer, and the return value is also a 32-bit signed integer

This bit conversion makes it possible for the two values to be treated as 0来 when applying a bit operation to a particular Nan and infinity value

If the bitwise operator is applied to a non-numeric application, the value is converted to a numeric and bitwise operation using number (), resulting in a numeric

//'|' Indicates bitwise-OR, an integer and 0 bitwise OR operation can get it itself, a decimal and 0 bitwise OR operation can get the rounding effect
Console.log (1.3 | 0);//1
Console.log (1.8 | 0);//1
Console.log (Infinity | 0);//0
console.log (-infinity | 0);//0 console.log
(NaN | 0);//0 console.log
(' 12px ' | 0);//0
console.log (' 12 ' | 0);//12

A signed integer uses the first 31 digits in 32 digits to represent an integer value, a 32nd digit for an integer symbol, 0 for a positive number, and 1 for a negative sign. The bits that represent the symbols are called sign bits, and the value of the sign bits determines the format of other bit values. Where positive numbers are stored in pure binary format, each of the 31 digits represents the power of 2. The first bit (called bit 0) represents 2 of 0 times, the second represents 2 1 times, and so on. The not-used bits are padded with 0, which is negligible

For example, the binary representation of a numeric 18 is 00000000000000000000000000010010, or a simpler 10010. This is a 5 significant bit, and the 5 bits themselves determine the actual value

Console.log ((a). ToString (2));/"10010"

Console.log (0b00000000000000000000000000010010);//18

Negative numbers are also stored as binary, but the format used is binary complement. To calculate a numeric binary complement, you need to go through the following 3 steps:

"1" to find the binary code of the absolute value

"2" For binary inverse code, the 0 will be replaced by 1, 1 replaced by 0

"3" To get the binary counter code plus 1

For example, to determine the binary representation of 18, you must first get a binary representation of 18, as follows:

0000 0000 0000 0000 0000 0000 0001 0010

Next, compute the binary inverse code as follows:

1111 1111 1111 1111 1111 1111 1110 1101

Finally, add 1 to the binary inverse code, as follows:

1111 1111 1111 1111 1111 1111 1110 1101
                   1
---------------------------------------
1111 1111 1111 1111 1111 111 1 1110 1110

Therefore, the binary representation of 18 is 1111 1111 1111 1111 1111 1111 1110 1110

ECMAScript will try to hide all of this information from us, and when we output a negative number as a binary string, we see only the binary code of the absolute value of the negative number plus a minus sign.

var num = -18;
Console.log (num.tostring (2));//'-10010 '

Bitwise operators can perform 7 operations, including bitwise non (not), bitwise-and (and), bitwise-OR (or), bitwise-Exclusive, or XOR, left-shifted, signed-right, and unsigned-right movement

Bitwise NON (NOT) 

A bitwise non-operator is represented by a wavy line (~), and the result of performing a bitwise non is the inverse of the return value. The essence is the negative value of the operand minus 1.

var num1 =;
var num2 = ~num1;
Console.log (num2);//-26

For an integer two times a bitwise not, you can get it itself; for a decimal number two times a bitwise not, you can get a rounding effect

Console.log (~~3);//3
Console.log (~~3.1);//3 console.log
(~~3.9);//3

Bitwise with (and)

Bitwise AND operator are represented by a ampersand (&), which has two operands. In essence, bitwise-and-action aligns each of the two values, and then performs an and operation on two numbers in the same position according to the rules in the following table

Bit results for the second digit of the first numeric value
1            1        1
1            0        0 0 1 0 0 0 0

Bitwise AND operation only two values of the corresponding bit is 1 o'clock to return 1, any one is 0, the result is 0

var iresult = & 3;
Console.log (Iresult);//"1"
Analysis follows:
 0000 0000 0000 0000 0000 0000 0001 1001
 3 = 0000 0000 0000 0000 0000 0000 0000 0011
----------- ----------------------------------and
= 0000 0000 0000 0000 0000 0000 0000 0001

bitwise OR (OR)

Bitwise OR operator by a vertical bar symbol (|) Indicates that there are also two operands, bitwise OR operation following this truth table

Bit results for the second digit of the first numeric value
1            1        1
1            0            1 0 1 1 0 0        0

A bitwise OR operation returns 1 if one bit is 1, and only two digits are 0 in the case of 0

var Iresult = 25 | 3;
Console.log (Iresult);//"27"
Analysis follows:
0000 0000 0000 0000 0000 0000 0001 1001
 3 = 0000 0000 0000 0000 0000 0000 0000 0011
-------------- ------------------------------
OR = 0000 0000 0000 0000 0000 0000 0001 1011

An integer and a 0 bitwise OR operation can get it itself, a decimal and 0 bitwise OR operation can get the rounding effect

Console.log (3.1 | 0);//3
Console.log (3.9 | 0);//3

Bitwise exclusive OR (XOR)

The bitwise XOR OR operator is represented by a caret (^) and also has two operands. The following is a bitwise XOR truth table

Bit results for the second digit of the first numeric value
1            1        0
1            0            1 0 1 1 0 0        0

Two values in a bitwise XOR return 0 at the same time, not return 1 at the same time

var iresult = ^ 3;
Console.log (Iresult);//"26"
Analysis follows:
 0000 0000 0000 0000 0000 0000 0001 1001
 3 = 0000 0000 0000 0000 0000 0000 0000 0011
-------------- -------------------------------
XOR = 0000 0000 0000 0000 0000 0000 0001 1010

"XOR" has a special use, two consecutive numbers a and b for three times, Aˆ=b, Bˆ=a, Aˆ=b, can exchange their values. This means that using XOR can swap the value of two variables without introducing a temporary variable

var a=10,b=9;
A ^= B, b ^= A, a ^= b;
Console.log (a,b);//9,10
Analyze the following
 a = 0000 0000 0000 0000 0000 0000 0000 1010
 b = 0000 0000 0000 0000 0000 0000 0000 1001
--------------- ------------------------------
 a1 = 0000 0000 0000 0000 0000 0000 0000 0011 a1

 = 0000 0000 0000 0000 0000 0000 000 0 0011 
 b = 0000 0000 0000 0000 0000 0000 0000 1001
---------------------------------------------
 b1 = 0000 000 0 0000 0000 0000 0000 0000 1010 = b1 0000 0000 0000 0000 0000 0000 0000 
 = 0000 0000 0000 0000 0000 0000 0 0011 
---------------------------------------------
 a2 = 0000 0000 0000 0000 0000 0000 0000 1001//a=
A2=10;b=b1=9

An integer with 0 bitwise XOR or can maintain itself, a decimal and 0 bitwise XOR or can be rounded

Console.log (3.1 ^ 0);//3
Console.log (3.9 ^ 0);//3

Move left

The left-hand operator is represented by a two less-than sign (<<), which moves all the digits of a numeric value to the left by the specified number of digits

For example, if you move the value 2 (binary to 10) to the left by 5 digits, the result is 64 (1000000)

var oldValue = 2;
var newvalue = oldvalue<<5;
Console.log (newvalue);//64

Moving left does not affect the sign bit of the operand. In other words, if you move 2 to the left 5 digits, the result will be-64

var oldValue =-2;
var newvalue = oldvalue<<5;
Console.log (newvalue);//-64

Move 0-bit left to achieve rounding effect

Console.log (3.1 << 0);//3
Console.log (3.9 << 0);//3

Sign Right Move

The signed right-shift operator is represented by two greater-than (>>), which moves the value to the right, but preserves the symbol bit (i.e., the sign). The symbolic right shift operation is the opposite of the left shift operation, that is, if you move 64 to the right 5 digits, the result returns to 2

var oldValue =;
var newvalue = oldvalue>>5;
Console.log (newvalue);//2

Similarly, in the shift process, the original value will also appear in the vacancy. Only this time the vacancy appears to the left of the original value, to the right of the symbol bit. At this point, ECMAScript fills all the empty spaces with the value of the symbol bit in order to get a full value

Right-shift can simulate 2 division operations

Console.log (5>>1);//2
Console.log (15>>1);//7

No sign Right move

The unsigned right-shift operator is represented by a 3 greater-than sign (>>>), which moves all 32 bits of the value to the right. For a positive number, the result of the unsigned right shift is the same as the signed right shift. Still with the previous symbol to the right to move, if the 64 unsigned right 5-bit, the result is still 2

var oldValue =;
var newvalue = oldvalue>>>5;
Console.log (newvalue);//2

However, negative numbers are not the same. First, the unsigned Right shift fills an empty space with a 0来, rather than filling the vacancy with the value of the symbol bit as if the symbol is moved right. Therefore, the unsigned right shift to a positive number is the same as the title right shift result, but the result for negative numbers is different. Second, unsigned right-shift operators treat negative binary codes as positive binary codes. Also, because negative numbers are represented in the binary complement form of their absolute values, they result in a very large number of unsigned right shifts.

var oldValue = -64;
var newvalue = oldvalue>>>5;
Console.log (NewValue)//134217726

To determine the binary representation of-64, you must first get a binary representation of 64, as follows:

0000 0000 0000 0000 0000 0000 0100 0000

Next, compute the binary inverse code as follows:

1111 1111 1111 1111 1111 1111 1011 1111

Finally, add 1 to the binary counter code, as shown below

1111 1111 1111 1111 1111 1111 1011 1111
                   1
---------------------------------------
1111 1111 1111 1111 1111 111 1 1100 0000

Move 5 digits to the right, as follows:

0000 0111 1111 1111 1111 1111 1111 1110 console.log

(0b00000111111111111111111111111110);//134217726

Common applications

"1" multiplication operation

Using left Shift (<<) to realize multiplication operation

Console.log (2 << 1);//4
Console.log (3 << 1);//6
Console.log (4 << 1);//8

"2" division operation

Using a signed right shift (>>) to simulate 2 division operations

Console.log (2 >> 1);//1
Console.log (5 >> 1);//2
Console.log (8 >> 1);//4
Console.log (9 >> 1);//4

"3" Value interchange

Use of XOR or operation (^) to achieve the effect of value interchange

var a=10,b=9;
A ^= B, b ^= A, a ^= b;
Console.log (a,b);//9,10

"4" Decimal rounding

Decimal rounding effect can be achieved by taking two times bitwise non, with 0 bitwise OR, with 0 bitwise XOR, left 0 bit, and right 0 bit.

Console.log (~~3.1),//3
Console.log (3.1|0),//3 console.log
(3.1^0);//3 console.log
(3.1<<0) ;//3
Console.log (3.1>>0);//3

"5" switch

The bitwise operator can be used as a switch to set the property of an object. Suppose an object has four switches, and each switch is a variable. So, you can set a four-bit binary number, and each bit of it 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 code above sets a, B, C, D four switches, each of which occupies a bits

Now suppose you need to open the ABD three switches, we can construct a mask variable

var mask = flag_a | Flag_b | Flag_d;
0001 | 0010 | 1000 => 1011

The above code "or" Abd three variables to get the mask value of the binary 1011

"OR operation" to ensure that the specified switch is opened
flags = Flags | mask;
"and operations" can be the current settings in general and the switch settings are not the same items, all off
flags = flags & mask;
XOR can toggle (toggle) The current setting, that is, the first execution can get the opposite value of the current setting, and then execute again and get the original value
flags = flags ^ mask;
"No operation" can flip the current setting, that is, the original setting is 0, the operation becomes 1, the original setting is 1, the operation becomes 0
flags = ~flags;

The above JavaScript operator--bit operator comprehensive introduction is small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.