简体   繁体   English

c 中的 printf 波浪号运算符

[英]printf tilde operator in c

I know that the ~ operator is NOT, so it inverts the bits in a binary number我知道~运算符不是,所以它反转二进制数中的位

unsigned int a = ~0, b = ~7;
printf("%d\n",a);
printf("%d\n",b);
printf("%u\n",a);
printf("%u\n",b);

I guessed 0 will be 1 and 7 (0111) will be 8 (1000) but the output was我猜 0 将是 1 和 7 (0111) 将是 8 (1000) 但 output 是

-1
-8
4294967295
4294967288

how did ~0 and ~7 become -1, and -8? ~0 和 ~7 是如何变成 -1 和 -8 的? also why is %u printing that long number?还有为什么 %u 打印那么长的数字?

The ~ operator simply inverts all bits in a number. ~运算符只是将数字中的所有位反转。

On most modern compilers, int is 32 bits in size, and a signed int uses 2's complement representation.在大多数现代编译器中, int的大小为 32 位,而有符号int使用2 的补码表示。 Which means, among other things, that the high bit is reserved for the sign , and if that bit is 1 then the number is negative.这意味着,除其他外,高位是为符号保留的,如果该位为 1,则该数字为负数。

0 and 7 are int literals. 07int字面量。 Assuming the above, we get these results:假设上述情况,我们得到以下结果:

  • 0 is bits 00000000000000000000000000000000b 0是位00000000000000000000000000000000b
    = 0 when interpreted as either signed int or unsigned int = 0当解释为有signed intunsigned int

  • ~0 is bits 11111111111111111111111111111111b ~0是位11111111111111111111111111111111b
    = -1 when interpreted as signed int = -1当解释为有signed int
    = 4294967285 when interpreted as unsigned int = 4294967285当解释为unsigned int

  • 7 is bits 00000000000000000000000000000111b 7是位00000000000000000000000000000111b
    = 7 when interpreted as either signed int or unsigned int = 7当解释为有signed intunsigned int

  • ~7 is bits 11111111111111111111111111111000b ~7是位11111111111111111111111111111000b
    = -8 when interpreted as signed int = -8当解释为有signed int
    = 4294967288 when interpreted as unsigned int = 4294967288当解释为unsigned int

In your printf() statements, %d interprets its input as a signed int , and %u interprets as an unsigned int .在您的printf()语句中, %d将其输入解释为有signed int ,而%u将其解释为unsigned int This is why you are seeing the results you get.这就是为什么你看到你得到的结果。

The ~ operator inverts all bits of the integer operand. ~运算符反转 integer 操作数的所有位。 So for example where int is 32-bit, 1 is 0x00000001 in hex and it's one's complement is 0xFFFFFFFE.因此,例如int是 32 位,1 是十六进制的 0x00000001,它的补码是 0xFFFFFFFE。 When interpreted as unsigned, that is 4 294 967 294, and as two's complement signed, -2.当解释为无符号时,即 4 294 967 294,而作为带符号的二进制补码,则为 -2。

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

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