The signed bit is the left most bit so >>> changes a 1 to 0 but not from 0 to 1, the >> keeps the sign bit so if it was 1 all bit shifted will be 1's and 0 with 0's, hopefully the bold has worked below
Which of the following results in a negative value of a?
A: int a = -1; a = a >>> 8;
B: byte a = -1; a = (byte)(a >>> 5);
C: int a = -1; a = a >> 5;
D: int a = -1; a = a >>> 32
A is:
11111111 11111111 11111111 11111111 >>> 8 gives you
00000000 11111111 11111111 11111111 this results in a big poistive int number.
B is:
converts the byte to an int then does the shifting, then casts back to a byte so bits look like this:
byte
11111111 promoted to 11111111 11111111 11111111 11111111 then shift to get
00000111 11111111 11111111 11111111 but we convert back to get the last 8 bits on the right hand side which is
11111111 byte -1
C is:
11111111 11111111 11111111 11111111 then shift with which ever the left most bit was which is 1 to get the same result
D is:
11111111 11111111 11111111 11111111 by 32 bits, I needed the pencil first time round, but then i noticed that it can only shift 31 times to give you +1 but 32 times is shifting 0 times so hence the same result of -1.
I normally find it easier writing out the bits first then trace out what will happen to the bits.
I hope this helps guys
Davy
[ February 18, 2004: Message edited by: Davy Kelly ]