The ~ operator in the c programming language
How does the operator work ~
in c?
can anyone explain the following code?
main()
{
printf("%d",~5);
}
output -6
The ~ operator in c is the bitwise NOT operator. So in your example
main()
{
printf("%d",~5);
}
will print
-6
Bits work as follows.
5 = 0000 0101
When you take a NOT byte, you flip all 1s and 0s, creating a new number
-6 = 1111 1010.
5
(possibly) 32-bit signed integer with bit 0x00000005
or binary representation :
0b00000000000000000000000000001010
~5
is a bitwise NOT of 5
which will be 0xFFFFFFFA
either binary:
0b11111111111111111111111111110101
Using two additions , that is -6
.
From standard C
4 The result of an operator ~ is the bit's 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). whole promotions are executed in the operand, and the result is an advanced type. If the promoted type is an unsigned type, the expression ~ E is equivalent to the maximum value represented in that type minus E.
So if you have 5 and sizeof (int) is 4, then you would have
00000000 00000000 00000000 00000101 => 5
11111111 11111111 11111111 11111010 => ~5 == -6
if you use unsigned int
instead int
like
int main( void )
{
printf("%u", ~5u );
}
then as the quote says
If the promoted type is an unsigned type, the expression ~ E is equal to the maximum value represented 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
The ~ bitwise NOT operator, it inverts the bits in a binary number:
so when we convert 5 to binary 5 = 0101
Then NOT 0101 means 1010 = -6. Mostly ~ is used to represent bitwise NOT.
So the answer is -6.