JavaScript operator--bitwise operator

Source: Internet
Author: User
Tags bitwise bitwise operators


xTable of Contents [1] binary [2] not [3] with [4] or [5] XOR [6] left shift [7] Shift right [8]>>>[9] apply the preceding words


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 good results. This article will cover the often overlooked operators in JavaScript--bit operators





Binary Representation


All the values in ECMAScript are stored in the IEEE-754 64-bit format, but the bitwise operators do not manipulate the 64-bit values directly, but instead operate with 32-bit signed integers, and the return value is also a 32-bit signed integer



This bit conversion allows the two values to be treated as a limit when the bit operation is applied to the special Nan and infinity values.



If you apply a bitwise operator to a non-numeric value, you will first use number () to convert it to a value and then apply a bitwise operation, resulting in a numeric value


//' | ' Represents a bitwise OR, an integer with 0 bitwise OR operation can get it itself, a decimal with 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

 


Signed integers represent integer values using the first 31 bits in the 32-bit, the integer sign with the 32nd digit, 0 for positive numbers, and 1 for negative numbers. The bit that represents the symbol is called the sign bit, and the value of the symbol bit determines the format of the other bit values. Where positive numbers are stored in a pure binary format, each of the 31 bits represents a power of 2. The first bit (called bit 0) represents 2 of 0 times, the second represents 2 1 times, and so on. Unused bits are filled with 0, which is negligible



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



Console.log ((). toString (2)); // "10010"Console.log (0b00000000000000000000000000010010); //  -


Negative numbers are also stored as binary, but the format used is twos complement. The following 3 steps are required to calculate the binary complement of a value:



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



"2" for binary anti-code, the 0 is replaced by 1, 1 is replaced by 0



"3" to get the binary anti-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, calculate the binary counter code as follows:



1111 1111 1111 1111 1111 1111 1110 1101


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




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


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



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



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 XOR (XOR), left shift, signed right shift, and unsigned right shift





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 value returned. Its essence is that the negative value of the operand minus 1



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


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




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




Bitwise VS (and)


The bitwise-AND operator is represented by a ampersand (&), which has two operands. In essence, bitwise and operations align each bit of the two numeric values, and then perform and operations on the two numbers in the same location according to the rules in the following table




Bits of first value Bits of second value Result
1 1 1
1 0 0
0 1 0
0 0 0


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



 
var iResult = 25 & 3;
console.log (iResult); // "1"
//analyse as below
  25 = 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




Bits of first value Bits of second value Result
1 1 1
1 0 1
0 1 1
0 0 0


Bitwise OR operation returns 1 if there is a bit of 1, and returns 0 only if two bits are 0



 
var iResult = 25 | 3;
console.log (iResult); // "27"
//analyse as below
25 = 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 0 bitwise OR operation can get 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 XOR OR (XOR)


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




Bits of first value Bits of second value Result
1 1 0
1 0 1
0 1 1
0 0 0


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



 
var iResult = 25 ^ 3;
console.log (iResult); // "26"
//analyse as below
  25 = 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

The "XOR operation" has a special application, with two numbers A and b being three times different or operations, Aˆ=b, Bˆ=a, Aˆ=b, which can interchange their values. This means that using an XOR operation allows you to swap the values of two variables without introducing temporary variables



 
var a=10,b=9;
a ^= b, b ^= a, a ^= b;
console.log(a,b);//9,10
//analyse as below
   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 0000 0011
   b = 0000 0000 0000 0000 0000 0000 0000 1001
---------------------------------------------
  b1 = 0000 0000 0000 0000 0000 0000 0000 1010
 
  b1 = 0000 0000 0000 0000 0000 0000 0000 1010
  a1 = 0000 0000 0000 0000 0000 0000 0000 0011
---------------------------------------------
  a2 = 0000 0000 0000 0000 0000 0000 0000 1001
// a = a2 = 10; b = b1 = 9 


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



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




Move left


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



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



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


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



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


Move left 0 to achieve rounding effect



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




Signed Right Shift


The signed right shift operator is represented by the two greater than sign (>>), which moves the value to the right, but retains the symbol bit (that is, the sign mark). A signed right-shift operation is just the opposite of a left-hand operation, which means that if you move 64 to the right by 5 bits, the result will change back to 2



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


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



Move right to simulate a 2 divide operation



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




Unsigned Right Shift


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



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


However, the negative numbers are different. First, the unsigned Right shift fills the empty space with zeros instead of filling the empty space with the value of the sign bit, as with the right shift of the symbol. Therefore, the unsigned right shift for positive numbers is the same as the right shift with the title, but the result for negative numbers is different. Second, the unsigned right shift operator treats a negative binary code as a positive binary code. Also, because negative numbers are represented in the absolute twos complement form, this results in a very large result after the unsigned right shift



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, calculate the binary counter 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 1111 1100 0000


Move the 5-bit to the right, as follows:



0000 0111 1111 1111 1111 1111 1111 1110

Console.log (0b00000111111111111111111111111110); // 134217726




Common applications


"1" multiplication operation



Use left shift (<<) to achieve multiplication



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


"2" division operation



Use the signed right Shift (>>) to simulate the 2 divide operation



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


"3" Value interchange



The effect of value interchange can be achieved by using XOR or operation (^)



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


"4" Fractional rounding



Decimal rounding effect can be achieved by taking two times bitwise non, 0 bitwise OR, 0 bitwise XOR, 0-bit shift left, 0-bit right shift



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


"5" switch



The bitwise operator can be used as a switch to set object properties. Suppose an object has four switches, and each switch is a variable. Then, a four-bit binary number can be set, and each bit of it corresponds to a switch



var // 0001 var // 0010 var // 0100 var //  +


The above code sets a, B, C, D four switches, each of which occupies a bits



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



var mask = flag_a | Flag_b | Flag_d; // 0001 | 0010 | + 1011


The above code gives the ABD three variables "or operations" to get a mask value of 1011 in binary



// "OR operation" can ensure that the specified switch is turned on
flags = flags | mask;
// "AND operation" can close all the items in the current setting that are different from the switch setting
flags = flags & mask;
// "Exclusive OR operation" can toggle the current setting, that is, the first time you can get the opposite value of the current setting, and then execute it again to get the original value
flags = flags ^ mask;
// "No operation" can reverse the current setting, that is, the original setting is 0 and becomes 1 after the operation; the original setting is 1 and becomes 0 after the operation
flags = ~ flags; 
Resources


"1" es5/bitwise arithmetic shift operator Https://www.w3.org/html/ig/zh/wiki/ES5/expressions
"2" Ruan one peak JavaScript standard reference Tutorial--operator HTTP://JAVASCRIPT.RUANYIFENG.COM/GRAMMAR/OPERATOR.HTML#TOC16
"3" JavaScript authoritative Guide (6th edition), chapter 4th expressions and operators
"4" JavaScript Advanced Programming (3rd Edition), chapter 3rd Basic Concepts



JavaScript operator--bitwise operator


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.