-2
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.......

eldarerathis
  • 35,455
  • 10
  • 90
  • 93
gourab
  • 1

3 Answers3

8

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.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
3

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
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
0

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.

Jesse Cohen
  • 4,010
  • 22
  • 25