I have the following code:
int a = -1;
System.out.println(a<<1);
This prints -2. That means the sign-bit is preserved. There is no unsigned left-shift operator in Java. My question is, what if you want to push off the sign-bit, as when you are using an int not to store a value, but to contain a pattern of bits that represent something?
During Arithmetic Shift Right (ASR), the MSB gets copied to the left, so the sign remains - that's clear. However in Arithmetic Shift Left (ASL), the sign could be in some cases lost, e.g. The original number was obviously positive since the MSB was 0, but the shifted number is negative since the MSB is 1.
Java supports two types of right shift operators. The >> operator is a signed right shift operator and >>> is an unsigned right shift operator. The left operands value is moved right by the number of bits specified by the right operand.
The signed left shift operator " << " shifts a bit pattern to the left, and the signed right shift operator " >> " shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand.
The unsigned right shift operator ( >>> ) (zero-fill right shift) evaluates the left-hand operand as an unsigned number, and shifts the binary representation of that number by the number of bits, modulo 32, specified by the right-hand operand.
For signed numbers, the sign bit is used to fill the vacated bit positions. In other words, if the number is positive, 0 is used, and if the number is negative, 1 is used.
Bitwise Left Shift Operator (<<) Left shift operator shifts the bits of the number towards left a specified number of positions.
The reason this prints -2
is not that the sign of -1
gets preserved, but that the bit at position 31 which gets shifted into position 32 happens to be 1
as well. In other words, the sign after shifting left by one is determined by the value of the second highest bit.
Binary representation of -1
has 1
s in all bits (an explanation can be found here), so the result remains negative as you continue shifting the number, until you shift out the last 1
bit after 32 shifts.
If you would like to drop the sign, you can mask the result to make it positive.
Why is there no unsigned left-shift operator in Java
Unlike shifting right, when the shift operator needs to make a decision on what to shift into the vacated position of the most significant bit, the value being shifted left determines the value of the new sign bit. The new zero bit is shifted into the least significant position, which does not have any special meaning.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With