The ~ operator in the c programming language
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
.
source to share
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
source to share