0
int x=10;
cout<<~x;

this code prints -11. if it was simple inversion then for 00001010 the bits should be 11110101, which on conversion to decimal is -117. I have tried searching but no luck pls tell what is happening here? I am using mingw compiler, if its of any help.

Sumit
  • 35
  • 5

3 Answers3

4

That is working as expected. "11110101" is -11 in two's complement.

As a side note, "int" is either 16 or 32 bits, so you're actually talking about "00000000 00001010" or "00000000 00000000 00000000 00001010" respectively.

rici
  • 234,347
  • 28
  • 237
  • 341
2

~x is equal to −x − 1. Therefore, ~10 = -10 - 1 = -11.

Using 1-byte , 10 is represented as 0000 1010. Its bit-wise NOT is 1111 0101. Generally computer represents signed integers in 2's complement format. So, decimal equivalent of 1111 0101 is -11, How?

An N-bit number w represented in 2's complement as aN-1aN-2....a0 can be converted to decimal as

enter image description here

Therefore,

1111 01012 = -1*27 1*26 + 1*25 + 1*24 + 0*23 + 1*22 + 0*21 + 1*20 = -128 + 117 = -11

haccks
  • 104,019
  • 25
  • 176
  • 264
  • 3
    2's complement is not the only method for representing signed integers, though it's by far the most common. The C standard explicitly permits either 2's-complement, 1's-complement, or sign-and-magnitude. – Keith Thompson Mar 30 '15 at 20:46
0

The ~ operator works as you think it does. It's just negative numbers don't work how you think they do. Negative numbers are encoded as a two's complement http://en.wikipedia.org/wiki/Two%27s_complement

Basically, the value of the highest bit is subtracted from the value of the lower bits.

  • 1
    Bear in mind C says nothing about how negative numbers are encoded - any system could in theory be used. – teppic Mar 30 '15 at 19:35
  • 2
    @teppic :That's not quite true. Starting with the C99 standard, it only permits 2's-complement, 1's-complement, and sign-and-magnitude. – Keith Thompson Mar 30 '15 at 20:47
  • @KeithThompson Ah, I didn't know C99 had limited the possibilities. Still, taking it for granted that 2's complement is always used is a very common thing. – teppic Mar 30 '15 at 20:54
  • The best idea might be not to rely on the behavior. Using bitwise operations only on unsigned types of a known size would solve the problem. – smeezekitty Mar 30 '15 at 20:58