Page 328 - Embedded Microprocessor Systems Real World Design
P. 328
Binary and hex numbers can be subtracted in the same way that decimal numbers are.
However, in computer hardware, subtraction is difficult to accomplish. Negative numbers
are difficult to store since there is no place for a minus sign. In a computer, subtraction is
usually performed by adding a negative number. A negative number is indicated by having
the most significant bit as 1. This is why the word width is important. On an &bit machine,
8OI6 is not the same as O08Ol6 on a l6bit machine. On the %bit machine, 8016 represents a
negative value.
Negative numbers can be represented in one’s compht or in two’s complement form. A
one’s complement number is formed by complementing all the bits in the number:
0010 0111 1011 0101 = 27B516
one’s complement = 1101 1000 0100 1010 = D8416
Note that the most significant bit is set, indicating that this is a negative number. You can
do math with one’s complement numbers as follows:
Hex: 3o1Ol6 - 27B!i16 = 3O1Ol6 + D8416 = 1085AI6 = 085AI6 = 2138
Decimal: 12,304 - 10,165 = 2139
Two notes about this: When we did the addition, the result was 1085A, but we threw away
the leading 1, leaving a result of 085A. This is because we’re working with a 16bit (4
hex digits) value. In a real lfibit computer, any carry beyond 4 digits would be lost. The
second thing to note is that the actual result we got, 213810, is one less than the right answer,
2139.
What happens if we do a subtraction and the result is negative? Let’s use the same
example, but subtract the larger number from the smaller one:
27B516 - 301016 = + CFEF16 = F7A416 = -85B16 = -213910
Note that the result of the addition, F7A4, had the most significant bit set, so we know it
was negative. Taking the one’s complement of the result gives us the answer, 2139.
The rules for one’s complement math are as follows:
A number to be subtracted is made negative and added.
To make a number negative, invert each bit in the number.
Add the two numbers.
Throw away any carry beyond the number of digits you’re using.
If the most significant bit (MSB) of the result is set, the result is negative.
If the MSB of the result wasn’t set, add one to the (positive) result.
Because we had to add 1 to the original result to get the right answer, why not make that
part of the number we’re subtracting? That is exactly what two’s complement is. To make a
two’s complement number, invert each bit in the number and add 1.
Two’s complement: 27B5, inverted = D84A. Add 1, result = D84B.
Now do that subtraction again in two’s complement:
Try the version that gives a negative result:
Appendix B 309