Hello,
I am kind of breaking my head trying to figure out how a bit representation
1111 1111 1111 1111 1111 1111 1111 1111 will be equal to -1.
Actually this is one of the exercises in Sun Certified Programmer and Developer for
Java 2 by Kathy Sierra and Bert Bates (Exercise 3 - 1 to be precise). The program is as follows.
Class BitShift
{
public static void main(
String args[])
{
int x = 1;
x = x << 1; // shifting left by 31 bits
x = x >> 1; // shifting right by 31 bits
System.out.println("After both the shifts, x: " + x);
}
}
If I do manually I get the above value (all 32 bits 1). But I can't figure out how this is equal to decimal value -1. Kathy and Bert must be obviously right and even when I ran the program I get output as x = -1. I guess I am messing up somewhere in converting the bit form to decimal form. For example I don't know how 1111 1111 1111 1111 1111 1111 1111 1110 is equal to decimal value -2. I am sorry if this is such a dumb question. But I just can't get it. Can someone please help me...
Thanks,
harsha.