Why 1s complement is -2

397 views Asked by At
int main()
{
       int a=1,b;
       b=~1;
       printf(""%d",b);
       return 0;
}

pls explain by showing bitwise operation it will be helpful to understand...

thanks in advance.......

3

There are 3 answers

0
Oliver Charlesworth On

It's exactly what you might imagine. 1 is 00000001 in binary (number of digits depend on size of int on your platform). ~1 performs a bitwise-inversion, i.e. 111111110. In two's complement (the most common system of binary arithmetic), this is equal to -2.

0
Mark Byers On

This identity should help you remember the behaviour of ~:

~x == -x - 1

Applying it to 1:

~1 == -1 - 1
   == -2

In bits:

 1 == ...0000000001
~1 == ...1111111110  # flip the bits

 0 == ...0000000000
-1 == ...1111111111  # two's complement representation for negative numbers
-2 == ...1111111110
0
Jesse Cohen On

Here is what is happening:

 1:  00000001
~1:  11111110

If you think about a signed integer, 0: 00000000 -1 -1: 11111111 -2: 11111110

Basically, start from zero and subtract two and see what you get.