Difference between >> and >>> in Scala

Kokizzu picture Kokizzu · Jun 20, 2013 · Viewed 11.7k times · Source

Is there any difference between >> and >>> operator in Scala?

scala> 0x7f >>> 1
res10: Int = 63

scala> 0x7f >> 1 
res11: Int = 63

scala> 0x7f >> 4
res12: Int = 7

scala> 0x7f >>> 4
res13: Int = 7

Answer

Jonathon Reinhart picture Jonathon Reinhart · Jun 20, 2013

The >> operator preserves the sign (sign-extends), while >>> zeroes the leftmost bits (zero-extends).

-10>>2
res0: Int = -3
-10>>>2
res1: Int = 1073741821

Try it out yourself.

This is not necessary in languages like C which has signed and unsigned types, unlike Java, which also has >>> (because it has no unsigned integers).