Negation of Bits

1.3k views Asked by At

The below code gives output -1.

#include <iostream>
using namespace std;
int main() 
{
    int x=0;
    cout<<~x;
    return 0;
}

But when I do the following modifications the answer changes to 4294967295. just want to know that why in case of int it is not giving -2147483647 which is 111.... 32 times

#include <iostream>
using namespace std;
int main() {
     unsigned int x=0;
    cout<<~x;
    return 0;
}
1

There are 1 answers

0
dbush On

The ~ operator inverts all bits in the operand. Here, x starts out as 0. So assuming an int is 4 bytes wide it has the following binary representation:

00000000 00000000 00000000 00000000

When all bits are inverted you get:

11111111 11111111 11111111 11111111

Assuming two's complement representation of integers, the value of this bit sequence is -1. Note that if you add 1 to this value all bits become 0 (i.e. -1 + 1 = 0).

In contrast, a value of -2147483647 has the following representation:

10000000 00000000 00000000 00000001