View Single Post
  #9   Spotlight this post!  
Unread 02-12-2002, 01:06
Jnadke Jnadke is offline
Go Badgers!
#0093
Team Role: Alumni
 
Join Date: Jan 2002
Location: Appleton, WI
Posts: 775
Jnadke is on a distinguished road
Send a message via ICQ to Jnadke Send a message via AIM to Jnadke Send a message via Yahoo to Jnadke
Two's Complement: Explained

I have taken a college course on programming x86 Assembly last year... I will try to explain it.

Two's complement is a way of representing negative numbers in the binary world. If you understand binary numbers (such as 00001000), and what they mean, then you will understand it.

The binary system works off powers of 2, versus the power of 10 in our standard counting system. In our system, the number 34 is actually represented mathematicaly as (4 x 10^0 + 3 x 10^1). The previous numbers are 4 and 30, added become 34. Binary is similar, but replace the 10's with 2, and the 3 and 4 are 0 and 1's. The number 34 would be represented as: 00100010. This is (0 x 2^0 + 1 x 2^1 + 0 x 2^2 + ... + 1 x 10^5 + 0 x 10^6 + ...). The numbers mulitplied by 0 are not counted. The numbers added are 2 and 32, which become 34. In the binary system, each 0 or 1 (digit) is called a "bit".


Negative numbers can be represented by one of two ways. The most obvious way would be to represent the numbers normally, and use a bit to represent whether the number is negative or not. For example, using this method, 34 would be (00100010) and -34 would be (10100010). Note that only values of up to 127 can be represented using 8 digits (bits) since the last value is a sign marker. This is true for two's complement as well.

The problem with the method above is that it is cumbersome when you needed to add the numbers. First, one would have to check the "marker" (sign) bit to see if it is negative. Then, you would have to devise a method that would add the numbers appropriately based on the sign bit. If you think about ways to do it, such as for the numbers 52 and -7, which makes 45 (00110100 and 10000111 makes 00101101). Any way you can think of would be cumbersome.

With Two's Complement, you can just add the binary numbers together, and you will get the answer. To get a number's two's compliment:
1. Take the binary number and switch the 0's to 1's and the 1's to 0's.
2. Add 1 (binary numbers "carry" like normal, so 0111 becomes 1000).

For example, 52 and -7:
52, as before, is 00110100.
7 is 00000111. Two's complement of this is 11111001.

When adding with two's complement, all one has to do is add the numbers. Remember to "carry" to the next digit when you add, like adding normally (just like when you calculate the Two's Complement).

00110100 (52)
11111001 (-7)
--------------------
00101101 (45)
__________________
The best moments of our lives fall in two categories: those that did happen and those that did not.