Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java left shift and fill with Zeros

Tags:

java

bit-shift

I want to do left shifting but filling with 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 leftshift

int number = 20 << 32 = 0000 0000 0000 0000 0000 0000 0001 0100 ;

I want to fill it with zeros just like >>> operator. So how I can do this?

like image 641
computerSPro Avatar asked Dec 02 '22 19:12

computerSPro


1 Answers

The << left shift operator will bring in zeros just as you want to.

The reason why there are 2 right shift operators (>> and >>>) is because in 2's complement form negative numbers have a bit value of 1 in the left-most bit position. The right shift operator >> will add the sign bit (1 in case of negative numbers, and 0 in case of positive numbers or zero) on the left side while the other (>>>) will always add zeros.

Both right shift operators have their use.

The language specification states that if bit shifting operators are applied on int since it is 32-bit long, only the 5 lowest bit is used to determine how many times to shift the number.

So if you shift by 32 which is 100000 in binary, it is equivalent to shift by 0 which means not to shift! And if you want to shift a 64-bit long, the 6 lowest bit is used only to tell how many times to shift.

like image 60
icza Avatar answered Dec 13 '22 10:12

icza