0

I have seen many sites and referred books and reach to a point that tilde(~) operator is used to do ones' complement but when i ran the following code snippet ,i got amazed by its output.Can anybody explain me the output ??

The output coming is -11 for the following code. Any help will be appreciated.

#include <iostream>
using namespace std;

int main() {
    int x=10;
    cout<<~x;
    return 0;
}
sagg1295
  • 177
  • 2
  • 11

2 Answers2

2

The tilde is a bitwise NOT operator, so what it does is invert bits. Since the int is signed, it uses 2's complement for negative numbers:

00001010 = 10
11110101 = -11
Mogzol
  • 1,405
  • 1
  • 12
  • 18
  • 2's complement of 10(00001010) is 11110110.u have written 1's complement of 10.then how -11 is coming as output i not able to understand tht – sagg1295 Oct 13 '16 at 15:40
  • Follow up question - why is it only operating on the 1 byte? (answer) it isn't, the rest of the bits are, which still on 2's compliment gives -11 – UKMonkey Oct 13 '16 at 15:40
  • It's operating on all the bytes, I just wrote the single byte since the others are kinda irrelevant in this scenario. And @sagg1295, I have written it right, invert the bits and add 1, you get 11. – Mogzol Oct 13 '16 at 15:42
  • @person66,sorry,i'm not able to understand the 2's complement of 10 ,my 2's complement is coming as 11110110 not mentioned by you above.can u please explain me the 2's complement of 10.It will be very grateful. – sagg1295 Oct 13 '16 at 16:05
  • @sagg1295 I don't think you understand how 2's complement works. 10 represented in 2's complement will still just be 10, because it's positive, so it doesn't change. To represent a negative number in 2's complement, say -11, you take positive 11, invert the bits, and add 1. There are plenty of resources online explaining how this works in more details, I'd suggest you read them if you're still confused. – Mogzol Oct 13 '16 at 16:40
  • I will also mention that if you did the above without adding 1 after inverting the bits, you would be doing 1's complement. The reason 2's complement is preferred is because it has only one '0' value. With 1's complement, there is both a 0, and a -0 (0 being all bits 0, -0 being all bits 1). – Mogzol Oct 13 '16 at 16:47
0

The operator concerned here is the http://en.cppreference.com/w/cpp/language/operator_arithmetic Bitwise not operator, which is reversing all the bits of the number 10, to get the number -11, which is resulted from reversing the bits.