Why doesn't Java support the <<<
(unsigned left shift) operator, but does support the >>>
(unsigned right shift) operator?
-
2Left shifts are strange to say the least.– Richard J. Ross IIICommented Mar 10, 2013 at 3:38
-
2As yourself this question: What would such an operator do?– MysticialCommented Mar 10, 2013 at 3:40
-
1What's even the point of an unsigned left shift? Other languages like JavaScript doesn't support it either.– Benjamin GruenbaumCommented Mar 10, 2013 at 3:42
-
@BenjaminGruenbaum correct. You don't have to worry about the sign of the number on a left shift– gtgaxiolaCommented Mar 10, 2013 at 3:43
-
ARM assembly language (and probably others) have synonyms for arithmetics and logical shift left, ASL and LSL. (IIRC, it has been almost two decades.)– Tom Hawtin - tacklineCommented Mar 10, 2013 at 4:18
4 Answers
Java adds the operator ">>>" to perform logical right shifts, but because the logical and arithmetic left-shift operations are identical, there is no "<<<" operator in Java.
from Shifts in Java...
-
why left shit operator is not supported in java please tell me with example if possible i am a beginner..– Cs ツCommented Mar 10, 2013 at 3:42
-
2
-
1The reason why
>>>
exists is the lack of unsigned datatypes in Java. In C/C++/C#, logical right shift is used when the left operand is unsigned, so you don't even see>>>
. Commented Mar 10, 2013 at 3:48
Why doesn't Java support the
<<<
(unsigned left shift) operator, but does support the>>>
(unsigned right shift) operator?
Because a (hypothetical) unsigned left shift operator would do exactly the same thing as the existing left shift operator.
(Hint: multiplying a binary integer by 2 entails left shifting by 1 and making the rightmost bit zero whether the integer representation is signed or unsigned. Write some examples on a piece of paper and test it for yourself.)
Why doesn't Java support the <<< (unsigned left shift) operator, but does support the >>> (unsigned right shift) operator?
That is because when you left shift the bits , the leftmost bit (AKA SIGNED Bit) is lost anyways.
Since unsigned left shift operator would do exactly the same thing as the existing left shift operator, we don't have it.
I think this is a design mistake. The << is not arithmetic shift. << is supposed multiply 2 if you do
0xF0FFFFFF << 4
it return a positive number! a negative number multiply 2 should never get a positive number. the << is doing <<< work.
-
So what number should it return? How do you represent
F0FFFFFF * 2^4
as a negative 64 bit signed value? (What actually << is actually doing is multiplying by a power of 2 ... followed by standard Javaint
overflow behavior; i.e. truncation of the high bits. It is not a mistake.) Commented May 26, 2021 at 6:48