November 16, 2023
If there’s one thing to know about two’s complement, it’s the following:
Negative numbers should have binary representations such that subtraction can be accomplished using the same algorithm as addition.
In order for this to work, the following is sufficient:
For all , let be the binary value such that under binary addition. Then is the binary representation of .
For example, knowing that
it follows that must be defined as .
Almost everything else about two’s complement is a consequence of these ideas. For example, this explains why the common trick for multiplying by is to flip all the bits and add one.
To prove that this representation of negative numbers satisfies subtraction, we can prove the following two statements.
Prove that the binary representation of each negative number is unique.
Exercise left to the reader.
Let represent binary addition via two’s complement. Prove that for any arbitrary and , .
If and , then the statement is directly applicable since when both operands are non-negative numbers.
If both and are non-negative and , then , where the first equality is true since binary addition of two positive number is simply addition. Applying to both sides we get , with the left-hand side simplifying to , satisfying the equality.
The rest is left as an exercise to the reader.
I came across this comment on HN which gives a nice intuition for Two’s Complement. We know that incrementing an integer of N bits will overflow at . So to represent negative numbers, we start at and go backwards to to get , to get , and so on and so forth.
The subscript in means this is a binary number. ↩