int n = 8;
n = n & n + 1;
The + operator has higher precedence, so in the absence of parentheses, we do that one first. Since n is 8, n+1 is 9.
n = n & 9
which means
n = 8 & 9
0000 0000 0000 0000 0000 0000 0000 1000 : 8
0000 0000 0000 0000 0000 0000 0000 1001 : 9
0000 0000 0000 0000 0000 0000 0000 1000 : 8 & 9 evaluates to 8
So n = 8
Next,
n<<=n/2;
which can be rewritten
n = n << n/2
Since n is 8 we can say
n = 8 << 8/2 (do the division first)
n = 8 << 4
0000 0000 0000 0000 0000 0000 0000 1000 : 8
0000 0000 0000 0000 0000 0000 1000 0000 : 8 << 4 evaluates to 128
So at the end n = 128.
-----------------------------------------------------------
int i = - 128;
System.out.println((byte)i << 1);
This tricky one fooled me at first.
i is -128. The first thing to do is to cast i to a byte, because there are no parentheses around i << 1. So we get a byte with the value of -128. The bit
pattern for that byte is
1000 0000 : -128, the lowest byte value
By casting -128 to a byte, we have discarded the high-order 24 bits of the int -128 (the bits on the left side), leaving us with the 8-bit byte shown above.
Next we want to use the << operator on that byte, which will promote both sides of the operation to int if they are byte, short, or char. So we're promoting (byte)(-128) to (int)(-128), which has the bit pattern
1111 1111 1111 1111 1111 1111 1000 0000 : -128
1111 1111 1111 1111 1111 1111 0000 0000 : -128 << 1 evaluates to -256
So the output will be -256
-------------------------------------------------------------
To convert a negative integer to its bit pattern: 1. Start with the negative integer (for example, -128)
2. Drop the negative sign (128)
3. Subtract one (127)
4. Write the bit pattern for the current result
0000 0000 0000 0000 0000 0000 0111 1111 (+127)
5. Flip the bits
1111 1111 1111 1111 1111 1111 1000 0000 (-128)
To convert a bit pattern starting with 1 to its negative integer value: 1. Start with the bit pattern
1111 1111 1111 1111 1111 1111 1000 0000 (we want to know what this is)
2. Flip the bits
0000 0000 0000 0000 0000 0000 0111 1111
3. Figure out the integer value for that bit pattern (127)
4. Add one (128)
5. Make it negative (-128)
[ May 07, 2005: Message edited by: Joe Sanowitz ]