Reputation: 37
How does ~
operator work in c?
can anyone explain the following code?
main()
{
printf("%d",~5);
}
output is -6
Upvotes: 3
Views: 317
Reputation: 310980
From the C Standard
4 The result of the ~ operator is the bitwise complement of its (promoted) operand (that is, each bit in the result is set if and only if the corresponding bit in the converted operand is not set). The integer promotions are performed on the operand, and the result has the promoted type. If the promoted type is an unsigned type, the expression ~E is equivalent to the maximum value representable in that type minus E.
So if you have 5 and sizeof( int ) is equal to 4 then you will have
00000000 00000000 00000000 00000101 => 5
11111111 11111111 11111111 11111010 => ~5 == -6
if you would use unsigned int
instead of int
,for example
int main( void )
{
printf("%u", ~5u );
}
then as it is said in the quote
If the promoted type is an unsigned type, the expression ~E is equivalent to the maximum value representable in that type minus E.
you would get. The maximum unsigned int value is
11111111 11111111 11111111 11111111 => UINT_MAX
-
00000000 00000000 00000000 00000101 => 5
=
11111111 11111111 11111111 11111010 => UINT_MAX - 5u
Upvotes: 2
Reputation: 9270
5
is (probably) a 32-bit signed integer with bit representation 0x00000005
, or in binary:
0b00000000000000000000000000001010
~5
is the bitwise NOT of 5
, which will be 0xFFFFFFFA
, or in binary:
0b11111111111111111111111111110101
Using two's complement, that is -6
.
Upvotes: 7
Reputation: 1180
The ~ operator is bitwise NOT, it inverts the bits in a binary number:
so when we convert 5 into binary 5=0101
Then the NOT 0101 means 1010=-6. Basically ~ is used to represent bitwise NOT.
So the answer is -6.
Upvotes: 0
Reputation: 340
The ~ operator in c is the NOT bitwise operator. So, in your example
main()
{
printf("%d",~5);
}
will print
-6
The bits work as follows.
5 = 0000 0101
When you take the NOT of a byte you flip all the 1's and 0's making the new number
-6 = 1111 1010.
Upvotes: 2