This week's book giveaway is in the JavaScript forum.We're giving away four copies of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js and have Paul Jensen on-line!See this thread for details.
Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Shifting operators

Paulo Aquino
Ranch Hand
Posts: 202

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?

Yingtao Jiang
Greenhorn
Posts: 13
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.

John Wolf
Ranch Hand
Posts: 64
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

 Don't get me started about those stupid light bulbs.