Silicon to Scripting 7
Representing numbers in binary and being able to add them is a large step in building a computer. The specific encoding we chose helped us in constructing the physical logic gate by making it simple.
So when it comes to negative numbers and subtracting, we could try to pick an encoding that helps us keep it simple.
Instead of figuring out how to do both addition and subtraction, when we want to subtract y from x: , we could make negative and then add it to : . But right now, we only can represent positive numbers with our encoding.
Again, try to come up with an encoding for negative numbers, it’s a good exercise.
Two’s Complement
Two’s complement is an example of a radix complement.
[A radix complement] is a technique to encode a symmetric range of positive and negative integers in a way that they can use the same algorithm for addition throughout the whole range.
This is the encoding that allows us to use instead of .
There are a few parts to this, so lets go through them one by one.
We need to “sacrifice” one bit of numerical storage for the “sign storage”. Modern computers use the highest (leftmost) bit.
1 001 => negative
0 011 => positive
Lets firgure out the actual encoding now.
0001 + ... = ...
If we try and use the same encoding, it doesn’t work
0001 + 1100 = 1101 # wrong
What can we do to make that work? If we use Two’s Complement, it does work.
0001 + 1100 = 1101
But how did we get there?
A more theoretical answer can be found on wikipedia. As for the algorithm, it is
- Start with the absolute value of the number
- Compute the bitwise inversion (invert all bits)
- Add 1 to the number, ignoring overflows
Lets take as an example:
0100
1011
1100
The “add 1” can be hard to reason why it’s there, but lets look at the range of number for a “signed 4 bit integer”: . The negative range always includes one more number because the original negative range of was shifted because and are the same.
references