aspose file tools*
The moose likes Beginning Java and the fly likes shift Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "shift" Watch "shift" New topic
Author

shift

Jello Yao
Greenhorn

Joined: Jan 05, 2003
Posts: 13
Here is the code about shift? Why the answer for i is -1; j is 0? Thanks!
1: int i = 1;
2: i <<= 31;
3: i >>= 31;
4: i >>= 1;
5:
6: int j = 1;
7: j >>= 31;
8: j >>= 31;
9:
10: System.out.println("i = " +i );
11: System.out.println("j = " +j);
John Lee
Ranch Hand

Joined: Aug 05, 2001
Posts: 2545
Why myy result are:
i = -2^31
j = 4
boyet silverio
Ranch Hand

Joined: Aug 28, 2002
Posts: 173
try doing it manually (or imagine) since the value dealt is only 1 and the movements are kinda "uniform" (>>31, <<31),
for i:
1. line up 32 zero locations (0000 0000 0000 0000 0000 0000 0000 0000). let's refer to each zero from left to write as 1st to 32nd
2. to represent int 1, change the 32nd zero to 1 to represent the binary of int i ( abbreviated as follows to 0000 0000 ... 0001).
3. to do i <<= 31, move the 'one' 31 times to the left (i.e. << ) and fill in a zero at the locations left by the 'one' as it is moved, which results to the first 0 being changed to 1
( 1000 0000 ... 0000 ).
note that the leftmost digit also indicates the sign (0 sign bit for positive and 1 sign bit for negative).
4. to do the operation i >> 31, (i now after previous operation is 1000 0000 ... 0000 ), move the 'one' 31 times to the right BUT because the symbol is >>, each of the location "stepped on" by the 'one' should be replaced with the sign bit (in this case '1'). This would result to
1111 1111 ... 1111
(all ones up to the 32nd). Getting the int value of this would result to -1; this would now be the i value printed out.
for j:
a. since you're dealing with int's, the format used is still 32 bit.
b. int j = 1 would be represented in binary as that of step #2 of i ( 0000 0000 ... 0001 ).
c. to do j >>= 31, move the 'one' (which is in the 32nd) 31 times to the right. since there is no 33rd, 34th locations.... the 'one' would just "fall off". the result would be all zeroes (from 1st to 32nd). and also, because the sign bit is '0', the location left by the 'one' is filled with zero.
0000 0000 ... 0000.
the value of j then becomes 0 even if same operation is repeated.
hope this helps.
[ January 09, 2003: Message edited by: boyet silverio ]
John Lee
Ranch Hand

Joined: Aug 05, 2001
Posts: 2545
Thanks! I overlooked ">>", which is sign shift, maintaining sign.
 
jQuery in Action, 2nd edition
 
subject: shift