Forums Register Login

Shifting operators

+Pie Number of slices to send: Send
 


int i = 1;
i <<= 31;//2
System.out.println(i);//3
i >>=31;//4
System.out.println(i);//5



Line 1 in binary is
0000 0000 0000 0000 0000 0000 0000 0001

Line 2 left shifts the value , in binary that's
1000 0000 0000 0000 0000 0000 0000 0000
So its value is -2147483648

Line 4 right shifts so it should be like this ?

1111 1111 1111 1111 1111 1111 1111 1111

I was wondering why the Line 5 prints -1?
+Pie Number of slices to send: Send
That binary pattern IS -1.
Because it is 2's complement. As the sign bit(the left most) is 1, so it is a negative number, in order to calculate its absolute value, you can do the following:
bitwise negation first, then plus 1.
So the all 1 pattern will become 000000...01.
+Pie Number of slices to send: Send
Paulo,

Another way to see this is : -

10000000 00000000 00000000 00000000

is the smallest -ve number

11111111 11111111 11111111 11111111

is the largest -ve number ... hence -1

Cheers!~
Sumit
"How many licks ..." - I think all of this dog's research starts with these words. Tasty tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 561 times.
Similar Threads
hexadecimal format
Shift operations
Question from Khalidmughal for >>> operator
Shift operator doubt
Operator precedence
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 06:27:38.