Two's component is one of the Signed number representations. Its principles is described as following. (refer to original at http://en.wikipedia.org/wiki/Two%27s_complement ) The 2n possible values of n bits actually form a ring of equivalence classes, namely the integers modulo 2n, Z/(2n)Z . Each class represents a set {j + k 2n | k is an integer} for some integer j, 0 ≤ j ≤ 2 n − 1. There are 2n such sets, and addition and multiplication are well-defined on them.
If the classes are taken to represent the numbers 0 to 2n − 1, and overflow ignored, then these are the unsigned integers. But each of these numbers is equivalent to itself minus 2 n. So the classes could be understood to represent −2n−1 to 2n−1 − 1, by subtracting 2n from half of them (specifically [2n−1, 2 n−1]).
For example, with eight bits, the unsigned bytes are 0 to 255. Subtracting 256 from the top half (128 to 255) yields the signed bytes −128 to 127.
The relationship to two's complement is realized by noting that 256 = 255 + 1, and (255 − x) is the ones' complement of x.
Example
−95 modulo 256 is equivalent to 161 since
- −95 + 256
- = −95 + 255 + 1
- = 255 − 95 + 1
- = 160 + 1
- = 161
And I have to say I can't understand the content well. The mathmatics concept is somehow complex to me. Why I got the idea to find out what's two's component is just because the Java puzzler below.public class JoyOfHex { public static void main(String[] args) { System.out.println( Long.toHexString(0x100000000L + 0xcafebabe)); } } What's the result? Obviously it should print 1cafebabe. Right? Wrong.During the computation, is promoted to the long value 0xffffffffcafebabeL.(I got missed here. Why?)So the result is: 0x00000000cafebabeL. Fix this problem as simple as using a long hex literal to represent the right operand.
Long.toHexString(0x100000000L + 0xcafebabe L)); Reference:
Java™ Puzzlers: Traps, Pitfalls, and Corner Cases By Joshua Bloch, Neal Gafter
www.wikipedia.org