~ is 1’s complement. So ~1010 is 0101 which is 5 in decimal not -11.
How ~10 is -11?
‘~’ is the bitwise NOT operation.
Bitwise NOT changes each bit to its opposite: 0 becomes 1, and 1 becomes 0.
And the sign bit also changes.
So ~10 is -11.
The result of ~ operator on a small number can be a big number if the result is stored in an unsigned variable. And the result may be a negative number if the result is stored in a signed variable (assuming that the negative numbers are stored in 2’s complement form where the leftmost bit is the sign bit).
Check this code -
#include
using namespace std;
int main()
{
unsigned int x = 1;
printf(“Signed Result %d \n”, ~x);
printf(“Unsigned Result %ud \n”, ~x);
return 0;
}
Output:
Signed Result -2
Unsigned Result 4294967294d
I got why sign changes but how is 10 becoming 11 ?
Because 10 is 1010
so when bits are changing it should become
1010, which is not 11.
Please correct if I am wrong.
10 in binary is represented as 01010. Leftmost bit is the sign bit. 0 for positive and 1 for negative.
So 10 = 0*(2^0) + 1*(2^1) + 0*(2^2) + 1*(2^3) - 0*(2^4)
Now reversing the bits - 10101
1*(2^0) + 0*(2^1) + 1*(2^2) + 0*(2^3) - 1*(2^4) = 1 + 0 + 4 + 0 - 16 = 5 - 16 = -11.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.