Page 329 - Embedded Microprocessor Systems Real World Design
P. 329
27B.516 - 301016 = 27B516 + cFFo16 = F7A516 = -85A16
(Inverting 301016 produces CFEF16 and adding 1 gives cFFO16)
Notice that the answer, F7A5, is correct since it is the two’s complement of 213910. So with
two’s complement, we don’t have to add 1 to positive results. The result is always right, no
matter what.
What happens if we add two negative numbers? Try this example:
-101016 - 201016 = EFFO16 + DFFO16 = cFEo16
CFEO is the two’s complement of 12320, which is the right answer. The rules for two’s
complement math are:
To make either number negative, invert all the bits and then add 1.
Add the two numbers.
If the MSB is zero, the result is positive and correct.
If the MSB is 1, the result is negative and correct in two’s complement form.
Overflow
As already mentioned, math on a computer is limited to the word width in use. If you try to
add 60,000 and 60,000, you get 120,000. On a l6bit computer, you’ll get the following:
6O,OOOlO = EA6010; EA6016 + EA6016 = 1D4C016 = D4C016
What happened to the 1 in the most significant position? It was dropped because this
is a 16bit (Migit) system and we can’t represent numbers larger than 65,535. In fact, this
addition turned the two positive numbers into a negative number. A computer that thinks
it is working in two’s complement will interpret this result (D4CO) as a negative number,
specifically -1 1O7Zl0. This is called overflow.
A 16-bit word can represent values from 0 to 65,535 (FFmI6). However, if the most
significant bit is used as a sign bit, then the same l6bit word can only represent values from
-32,768 (8OOOI6) to +32,767 (7FFFI6). There are still 65,536 values, but half of them are
negative. Note that the most negative value isn’t FFFF16. The most negative value is 8OOOI6.
FFm16 is negative 1, and it’s what you get if you start with 0000 and subtract 1. Try it.
When you do math on a computer, the hardware doesn’t necessarily know that you are
using two’s complement. When the MSB is treated as a sign bit, the number is said to be a
signed number. When the MSB is part of the number, you can’t have negative values, and the
number is called an unsigned number. Thus, if you want to add 30,000 and 30,000, you can
treat the result (EA6OI6) as an unsigned, positive result (60,00010) or as a signed, negative
number (-553610 in two’s complement).
Of course, with a wider word (32 or 64 bits), the range of values-both positive and
negative-is much greater.
Number Suffixes
One final word about the hexadecimal number system involves the abbreviation K (for kilo).
When you see the suffix K attached to a number in electronics or finance, it implies a
310 Appendix B