

The 8051





Using 2's Compliment for Dealing with
Positive and Negative Numbers 



So far, when looking at data stored in RAM we have been
thinking of this data as 8bit positive numbers with a range of 0 to
255. However, in the real world most data can be both positive and
negative (for example, a range of temperatures). 

Therefore, we need to examine the system used by
microcontrollers for storing and manipulating positive and negative
numbers. 



1's Compliment 

To get the 1's compliment of a number each bit is inverted.
Three examples are given in the table below: 



8bit number 
1's compliment 
11010001 
00101110 
11111111 
00000000 
01000110 
10111001 




2's Compliment 

To get the 2's compliment of a number 1 is added to the 1's
compliment of the number. The three examples from the table above are
converted into 2's compliment below.




8bit number 
2's compliment 
11010001 
00101111 
11111111 
00000001 
01000110 
10111010 




To change the 2's compliment of a number back to its original
value, simply get the 2's compliment again. Try it with the examples
above. 





The Sign Bit 

In the C programming language and in microcontrollers, a
signed number is a number which can be either positive or negative
while an unsigned number can only be positive. 

With signed numbers, the MSB is used to determine whether or
not the number is positive or negative. If the MSB is 0 then the number
is positive while if the MSB is 1 the number is negative. 

Therefore, a positive number is stored unchanged. For
example, the signed number 86 (DEC) is stored the same as the unsigned
equivalent (01010110  is binary for 86). 

However, a negative number is stored as the 2's compliment of
its absolute value. For example, 86 is stored as the 2's compliment of
86 (10101010 is the 2's compliment of 01010110). 





Converting Signed Binary Numbers to Decimal 

Since an MSB of 0 means a positive number and an MSB of 1
means a negative number, you may be thinking it is necessary for the
system to test the MSB in order to determine the sign of a number. This
is not so. Converting signed numbers from binary to decimal is exactly
the same as converting unsigned numbers from binary to decimal, except
for one small difference  the MSB is negative. 

2^{7} 2^{6} 2^{5} 2^{4}
2^{3} 2^{2} 2^{1} 2^{0}








Copyright (c) 20052006 James Rogers
