Search code examples
scalaoperatorsbit-shift

Difference between >> and >>> in Scala


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

Solution

  • 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).