[Courses] C Programming For Absolute Beginners, Lesson 2: Fun With Printf, Scanf, Puts, and Variables

Sachin Divekar ssd532 at gmail.com
Wed Mar 7 01:56:03 UTC 2012


On Wed, Mar 7, 2012 at 5:52 AM, Kevin Cole <dc.loco at gmail.com> wrote:

> Oh what the heck. ;-)
>
> Negative binary numbers:  If you only have a limited number of little
> magnets (or transistors or whatever the frig they are) to represent each
> bit in a number, then anything bigger just "overflows" the space
> available.  Imagine you have a shelf with room for eight books, and you
> keep adding a book on the right, and pushing the books to the left to make
> room for the new addition. When you add book #9, the first book has been
> pushed all the way to the left and falls off the shelf.
>
> So,  in our previous 4-bit computer, what happens when we add 1 to 15
> (1111)?  If we had 5 bits, we'd get 10000, a.k.a. 16. But, we don't and so
> the last book fell off the shelf and we get 0000 -- and on any decent
> system a warning that you've got an overflow error.
>
> Now, for negative numbers... The sum of a positive number and its negative
> cousin should equal 0.  So, for SIGNED arithmetic, we've just established
> that 0001 + 1111 = 0000, given the constraint of only four bits to work
> with.  Therefore, by perverse logic, 1111 must be negative 1. ;-)
>
> The way to convert a positive binary integer to its negative, is to use
> the "two's complement".  In this case, a complement isn't about telling the
> number how sexy or smart it is. ;-)  It's more akin to the idea that
> certain wines complement certain foods.  In this case it means the opposite
> state of a bit:  The one's complement of 1 is 0 and vice versa.  So, the
> one's complement of 1001 is 0110, the one's complement of 1111 is 0000,
> etc.  Initially, you might be tempted to think we could use the one's
> complement of a number to represent its negative value.  But there are a
> few edge cases where it gets illogical.
>
> To get the two's complement, add 1 to the one's complement:  Two's
> complement of 1001 (decimal value 9) is 0110+1 = 0111 (decimal -9 in 4-bit
> signed arithmetic).  If you add the two binary values together:
>
> 111
> 1001
> 0111
> ----
> 0000
>
> 1+1 = 2, which in binary is 10. Carry the 1. 1+0+1 = 10. Carry the 1.
> 1+0+1 = 10. Carry the 1. 1+1+ 0 = 10. Carry the 1.  Overflow. But in this
> case, since we know we're dealing with signed arithmetic, the overflow
> doesn't count, and the last digit drops off, giving us 0000.
>
> Voila!
>
> (We now return you to your regularly scheduled broadcast.)



Dear Kevin,

Indeed, a very very good explanation of complements and negative binary
numbers.
Thanks for sharing.

--
Regards,
Sachin Divekar


More information about the Courses mailing list