Java left shift and zero padding
I want to do a left shift, but filling in zero, just like
int number = 20 >>> 10 = ( 0000 0000 0000 0000 0000 0000 0001 0100 )
int number = 20 >>> 32β = ( 0000 0000 0000 0000 0000 0000 0000 0000 )
I want to do the same with left shift since there is no <<<operator for left shift
int number = 20 << 32 = 0000 0000 0000 0000 0000 0000 0001 0100 ;
I want to fill it with zeros just like the β> operator. So how can I do this?
source to share
The shift operator <<
will cast zeros the way you want.
The reason there are two right shift operators ( >>
and >>>
) is because in 2's complement form, negative numbers have a bit value 1
at the leftmost position. The right shift operator >>
will add the sign bit ( 1
in the case of negative numbers and 0
in the case of positive numbers or zero) on the left side, while the other ( >>>
) will always add zeros.
Both right shift operators use.
The language specification states that if the bit shift operators are applied to int
, since it is a 32-bit length, only the least significant 5 bits are used to determine how many times to shift a number.
So, if you shift by 32, which is 100000
in binary, it is equivalent to shifting by 0, which means no shift! And if you want to shift 64-bit long
, the least significant bit is only used to indicate how many times to shift.
source to share
You need to use the long type and only use the least significant 32 bits. Use and operator for this.
long intMask = 0x00000000FFFFFFFFL;
long x = 0x00000000FFFFFFFFL;
x = x<<32;
int xi = (int)(x & intMask);
System.out.println("xi=" + xi); //Result will be 0
See question: Declaring an unsigned int in Java
source to share