You're correct in that the formula is wrong. The formula doesn't account for N. The best way to understand bit shifting is to understand the underlying bit representation of the integral numbers.
The primitive int is 32 bits wide. The most significant bit is the sign bit (0 for positive, 1 for negative). It is base 2 representation so:
<PRE>
0000 = 0 (first bit is the right most bit, read from right
0001 = 1 to left)
0010 = 2
0011 = 3 Each bit position has a value associated with it.
0100 = 4 bit 0 has 2 to the power of 0
0101 = 5 bit 1 has 2 to the power of 1
0110 = 6 bit 2 has 2 to the power of 2
0111 = 7 so on...
1000 = 8 The bit value acts like a switch.
1001 = 9
1010 = 10
1011 = 11
1100 = 12
1101 = 13
1110 = 14
1111 = 15
010000 = 16 ...
</PRE>
This works for positive numbers. To represent a negative number,
Java uses 2's complement. Start with the positive representation of the number, invert each bit, then add 1.
So, for example, what does -1 look like in bits.
- Start with 1.
00000000 00000000 00000000 00000001 (32 bits wide)
- Invert each bit.
11111111 11111111 11111111 11111110
- Add 1
11111111 11111111 11111111 11111111
That's what -1 looks like in 2's complement.
Let's try -5.
- Start with 5.
00000000 00000000 00000000 00000101
- Invert each bit.
11111111 11111111 11111111 11111010
- Add 1
11111111 11111111 11111111 11111011
Now, let's shift -5 to the right unsigned by 2 (-5 >>> 2).
Unsigned means we add zero from the left side.
So, taking -5, we end up with:
00111111 11111111 11111111 11111110
The bits on the right side fell off and are gone.
This ends up being 1073741822.
Formulas are nice but it shouldn't substitute for basic understanding of binary representation and binary arithmetic. My attempt here is by no means complete. I would suggest looking up reference material explaining binary numbers. It will make shift operators a lot easier to understand.
[This message has been edited by Sam Wong (edited December 12, 2000).]