简体   繁体   English

运算符~c编程语言

[英]Operator ~ in c programming language

How does ~ operator work in c? ~操作符如何在c中工作?

can anyone explain the following code? 任何人都可以解释以下代码?

main()
{
   printf("%d",~5);
}

output is -6 输出为-6

5 is (probably) a 32-bit signed integer with bit representation 0x00000005 , or in binary: 5 (可能)是一个32位有符号整数,位表示为0x00000005 ,或者是二进制:

0b00000000000000000000000000001010

~5 is the bitwise NOT of 5 , which will be 0xFFFFFFFA , or in binary: ~5是按位的NOT 5 ,这将是0xFFFFFFFA ,或在二进制:

0b11111111111111111111111111110101

Using two's complement , that is -6 . 使用二进制补码 ,即-6

The ~ operator in c is the NOT bitwise operator. c中的〜运算符是NOT按位运算符。 So, in your example 所以,在你的例子中

   main()
{
       printf("%d",~5);
}

will print 将打印

-6

The bits work as follows. 这些位的工作原理如下。

5 = 0000 0101 5 = 0000 0101

When you take the NOT of a byte you flip all the 1's and 0's making the new number 当你取一个字节的NOT时,你翻转所有的1和0来制作新的数字

-6 = 1111 1010. -6 = 1111 1010。

From the C Standard 来自C标准

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). 4运算符的结果是其(提升的)操作数的按位补码(也就是说,当且仅当转换后的操作数中的相应位未置位时,才会设置结果中的每个位)。 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. 如果提升类型是无符号类型,则表达式~E等于该类型中可表示的最大值减去E.

So if you have 5 and sizeof( int ) is equal to 4 then you will have 所以,如果你有5并且sizeof(int)等于4那么你将拥有

00000000 00000000 00000000 00000101 => 5
11111111 11111111 11111111 11111010 => ~5 == -6

if you would use unsigned int instead of int ,for example 例如,如果你使用unsigned int而不是int

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. 如果提升类型是无符号类型,则表达式~E等于该类型中可表示的最大值减去E.

you would get. 你会得到的。 The maximum unsigned int value is 最大unsigned int值是

11111111 11111111 11111111 11111111 => UINT_MAX
-
00000000 00000000 00000000 00000101 => 5
=
11111111 11111111 11111111 11111010 => UINT_MAX - 5u

The ~ operator is bitwise NOT, it inverts the bits in a binary number: 〜运算符是按位NOT,它以二进制数反转位:

so when we convert 5 into binary 5=0101 所以当我们将5转换为二进制5 = 0101时

Then the NOT 0101 means 1010=-6. 然后NOT 0101表示1010 = -6。 Basically ~ is used to represent bitwise NOT. 基本上〜用于表示按位NOT。

So the answer is -6. 所以答案是-6。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM