Fabian S
Fabian S

Reputation: 55

difficulty understanding signed not

I'm having trouble understanding why c equals -61 on the following program:

   main() {
       unsigned int a = 60;     // 60 = 0011 1100   
       unsigned int b = 13;     // 13 = 0000 1101
       int c = 0;           
       c = ~a;          //-61 = 1100 0011
       printf("Line 4 - Value of c is %d\n", c );
   }

I do understand how the NOT operator works on 0011 1100 (the solution being 1100 0011). But I'm not sure why the decimal number is increased by 1. Is this some sort of type conversion from unsigned int (from a) into signed int (from c) ?

Upvotes: 0

Views: 51

Answers (1)

mcfisty
mcfisty

Reputation: 207

Conversion from a positive to a negative number in twos complement (the standard signed format) constitutes a bitwise inversion, and adding one.

Note that for simplicity I am using a single signed byte.

So if 60 = 0011 1100
Then c   = 1100 0011 + 1
         = 1100 0100

And for a signed byte, the most significant bit is negative, so

c = -128 + 64 + 4 = -60

You need to add 1 to account for the fact that the most significant bit is -128, while the largest positive number is 0111 1111 = 127. All negative numbers have a 1 for -128 which needs to be offset.

This is easy to see when you look at converting 0 to -0. Invert 00000000 and you get 11111111 and adding one gets you back to 00000000. Do the same with 1 to -1 and you get 11111111 - the largest possible negative number.

Upvotes: 2

Related Questions