Tuesday, October 18, 2016

Caution JavaScript Ahead - Difference between >> & >>>

Introduction

As we know inside the computer everything is kept as binary 1 or 0. We can shift the bits to left or right using our program for accomplishing various tasks. In JavaScript there is one more feature for right shifting called unsigned shifting that is what we are going to discuss in this post. Below are some prerequisites before we discuss the same.

Bitwise operations happen on 32 bit numbers only

The first thing we need to know about JavaScript bit manipulation is that it works for 32 bit numbers.

Negative numbers are represented as 2's complement

When the negative numbers are stored, they use 2's complement form.

Signed right shifting >>

Here the sign of the number will not be changed due to shifting. The sign bit will make copies and propagate to the right side when the bits are shifted. An example below. 


var binary= (7>>1).toString(); 
console.log(binary);
binary= (-7>>1).toString(); 
console.log(binary);

Output - 
3
-4

How we got 3 is clear as its simple right shift. The -4 came instead of -3 because it uses 2's complement. That details are there in one of my previous post.

Unsigned right shifting >>>

Lets see what will happen in unsigned shifting. The main difference is that the sign bit just won't propagate to the right side without making copy. Hence the sign will change. Since the bits added to the left are 0s the sign of -ve number will change to +ve. 


var binary= (7>>>1).toString(); 
console.log(binary);
binary= (-7>>>1).toString(2); 
console.log(binary);

Output - 
3
2147483644

The negative number became positive. Lets see how that happened.
11111111 11111111 11111111 11111001 - 2's complement of -7
01111111 11111111 11111111 11111100 - After shifting bits one time to right

Look at the left most sign bit it changed to 0 which means its a +ve number now. What is that number? Its 2147483644.

Left shifting <<

The point to remember here is that the unsigned shifting is not there for left shifting operation. The sign bit can be overwritten by the bit right to that and that becomes the new sign of the number.


var binary= (1<<31).toString
console.log(binary);

Output - 
-2147483648

How this -ve number came?
00000000 00000000 00000000 00000001 - 1 in 32 bit rep
10000000 00000000 00000000 00000000 - shifted left 31 times 

The sign bit is negative hence its in 2's complement. Get the number from this 2's complement format. Its -2147483648

References

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators
http://stackoverflow.com/questions/14061999/why-does-0x80000000-1-in-javascript-produce-a-negative-value
http://blog.revathskumar.com/2014/03/javascript-shift-operators.html
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER

No comments: