Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between >> and >>> operators in JavaScript

Running the following JavaScript code shows 63 in both cases:

  alert( 0xff >> 2 );
  alert( 0xff >>> 2 );

What is the differences between >> and >>>? Their results seem to be equal.

like image 383
0x90 Avatar asked Nov 28 '25 17:11

0x90


2 Answers

>> is a bitwise operator, which shift the bits to the right. Any bits at the right are lost.

 8 = 1000
     ^-->1
   = 0000 = 0

>>> does the similar thing as >>, but it's unsigned, which means that it ranges from 0 to 232-1 instead of +/- 231-1.

To see the result of my first statement in action, let's use the bitwise operator to floor a number:

1.234 >> 0         =  1 // Ok, fraction lost
1.234 >>>0         =  1 // Ok, fraction lost
-1.23 >> 0         = -1 // Ok, fraction lost
-1.23 >>>0         = 4294967295 // (negative numbers are not within the range)

Math.pow(2,31) >> 0  = -2147483648 // 2^31 is out of range
Math.pow(2,31) >>> 0 = 2147483648

So, when the upper boundary of a range is exceeded, the calculation will continue at its lower range, and vice versa (eg <<). The following illustrates shows what happens when you use n = (n + 1) >> 0, and >>> 0, for n starting at the lowest boundary.

// Signed       Unsigned
     >>            >>>
-2147483647             0
-2147483646             1
...                   ...
 2147483646    4294967294
 2147483647    4294967295
-2147483647             0
-2147483646             1
like image 106
Rob W Avatar answered Nov 30 '25 06:11

Rob W


It is the Unsigned Right Shift Operator.

like image 29
adarshr Avatar answered Nov 30 '25 07:11

adarshr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!