Hi, here is a example of ~ operator: int i = 1; System.out.println(~i); the result is -2 . But I think the binary transform should be like this : 00000000 00000000 00000000 00000001 i 11111111 11111111 11111111 11111110 ~i Who can tell me what is the real transform in this example?
What you are looking for is a thing called "2's Complement" and it follows like this: If you are going to represent a number using (for example) 8 bits, you can count from 0000 0000 (ie 0) to 1111 1111 ( ie 2^9 - 1 = 511) This only lets you store positive numbers. If you 'give up' the first bit and use it as 'sign bit' to represent positive or negative, and store negative numbers as the bitwise-or of the positive number, you can now count from 1000 0000 (-1 * 2^8-1 = -255) to 0111 1111 (1 * 2^8-1 = 255) This would be fine, but you notice that 1111 1111 = -0 0000 0000 = +0 ie we have 2 representations for '0' To get around this, we store negative numbers as the bitwise-or of the positive number, then add one to regain that extra 'bit' Now: 1000 0000 equals -1 * (2^8-1+1) = -256 1111 1111 equals -1 * (0 + 1) = -1 0000 0000 equals 1 * 0 = 0 0111 1111 equals 1 * (2^8-1) = 255 I hope I got it right, its been a while since I had to do this. Dave