Is there any difference between the operator β and β> 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
The operator >> saves the sign (sign-extends), and >>> resets the leftmost bits (zero-extends).
>>
>>>
-10>>2 res0: Int = -3 -10>>>2 res1: Int = 1073741821
Try it yourself.
This is not necessary in languages ββlike C, which have signed and unsigned types, unlike Java, which also has >>> (since it does not have unsigned integers).
Note: with SLIP 30 (November 2015), Scala may end (in 2016 2017?) With 4 βprimitiveβ types for representing unsigned integers: UByte , UShort , UInt and ULong .
UByte
UShort
UInt
ULong
This would affect the bit shift operations on UInts and ULongs , which also illustrates the difference between >> and >>> :
Left shift << and logical right shift >>> behaves in an obvious way.The case of arithmetic shift in shift >> is controversial.We argue that it should not be available for unsigned integers for two reasons:First, the arithmetic right of the shift does not matter for unsigned integers. The correct arithmetic shift if >>> . Therefore, like unary_- , it should not be entered.Secondly, existing languages ββthat have unsigned integer types, such as the C family, actually provide different semantics >> depending on whether it has a signed or unsigned operand :A >> in the unsigned operand is not signed. It would be confused with the C developer for x >> 3 by the signature extension in Scala, but it would be just as confusing for the Scala developer that x >> 3 would not be decrypted. Therefore, we prefer to completely exclude it, and let a compiler error occur.If an algorithm based on bit-twiddling needs a character shift right, it can always be reinterpreted as signed, perform the operation, and reinterpreted as unsigned: (x.toInt >> 3).toUInt .Note: the current implementation provides >> until we agree on this.
Left shift << and logical right shift >>> behaves in an obvious way.
<<
The case of arithmetic shift in shift >> is controversial.We argue that it should not be available for unsigned integers for two reasons:
unary_-
x >> 3
If an algorithm based on bit-twiddling needs a character shift right, it can always be reinterpreted as signed, perform the operation, and reinterpreted as unsigned: (x.toInt >> 3).toUInt .
(x.toInt >> 3).toUInt
Note: the current implementation provides >> until we agree on this.
They have the same meaning as in Java. The signed left shift operator "<shifts the bit pattern to the left, and the signed left shift operator" β "shifts the bit to the right. The bit diagram is set by the left operand and the number of positions is shifted by the right operand. The unsigned right shift operator" β> shifts zero to the leftmost position , and the leftmost position after "β" depends on the expansion of the character.