Hello,

How does two's complement work? I looked at some sites and I don't have a problem with adding integers but the binary really confuses me. Any ideas?

Thanks..

Printable View

- 10-19-2007alyeskatwo's complement
Hello,

How does two's complement work? I looked at some sites and I don't have a problem with adding integers but the binary really confuses me. Any ideas?

Thanks.. - 10-19-2007sh3rpa
if the left-most bit is 0, the number is positive

if the left-most bit is 1, the number is negative

adding is straightforward:

0 + 0 = 0

0 + 1 = 1

1 + 1 = 0 carry a 1

To subtract (if i remember correctly) you invert each bit of what you're subtracting, add 1, then add the numbers.

You must also always take into consideration overflow.

Basically if you're final carry out number (be it 1 or 0) does NOT match the previously carried value, you have an overflow. - 10-19-2007sh3rpa
also, it's been a while so if i was wrong dont hate me!

Here's a link to my old teacher's site:

http://www.cs.odu.edu/~ibrah_k/cs170/sched.htm

Lecture 3 goes over how to represent binary numbers, signed magnitude, one's complement, and two's complememnt. Hope it helps! - 10-19-2007DougDbug
**FYI -**The Windows calculator shows two's complement when you switch it to binary.*Start -> Programs -> Accessories -> Scientific -> Binary*. ...Enter -1 (decimal), click*binary*, and look at the result.

And, with most "real world" C/C++ it doesn't matter! Since cin and cout don't support binary, you can't "see" the binary data without some extra code, and**binary numbers are rarely used directly in programs.**(We usually use hexadecimal when we want to "see" the bits... You can easily learn to convert between hex & binary in your head.)

When we are dealing the binary/bits,**we usually treat the variable as a "bit pattern" rather than an integer value.**(Just as you are usually not concerned with the decimal value of an ASCII 'A'.) So, although we might be interested in the state of the MSB (most significant bit), we (usually) don't care about the integer's decimal value, or if it represents a positive or negative number!

The main purpose for beginning programmers learning about binary numbers is**to understand the limitations of the variable types,**and to learn why things can get really fouled-up if you don't understand and respect those limits. - 10-21-2007alyeska
Thanks sh3rpa and Doug.. I'll keep that in mind...

-Shelah