Javascript Bitwise Shift
In this article, we will see about the javascript bitwise shift. In JavaScript, there are two types of shift operators:
- Left shift bitwise operator
- Right shift bitwise operator
Before seeing these two types, we should know what is bitwise operators.
What is the Bitwise operator in JavaScript:
It performs operations on bits of a given decimal number (i.e. 0s and 1s). It converts the given decimal numbers to their binary equivalent number, then performs the operation on bits of the converted binary equivalent numbers and returns the result as a decimal number .
Right Shift Bitwise operator:
Double greater-than sign “>>” indicates the Right shift bitwise operator. It shifts the bits of the first number to the right by a number of positions indicated by the second number.
Example :
document.write(40 >> 2); // 10
- In the above code, When we shift the bits of the number 40 to the right side by 2 positions, we get 10.
- See the below image after shifting two position right to the number system.
- Let me explain more clearly, in the binary number system “00101000” indicates 40. Underneath 32 we have 1 and underneath 8 we have 1, so 32+8=40.
- See the below image after shifting two position right to the number system.
Here we have the value of Underneath 8 and 2, so 8+2 =10.
Left Shift Bitwise operator
Double less-than sign “<<” indicates left shift bitwise operator. It shifts the bits of the first number to the left b number of positions indicated by the second number. It is similar to right shift operator.
Example:
document.write(40 << 2); //160
- In the above code, we use the left shift operator between the numbers 40 and 2. When we shift the bits of the number 40 to the left side by positions, we get 160.
- It works the same as the right shift bitwise operator. In the binary number system “00101000” indicates 40.
- After shifting 2 position right the output will be displayed 160.