[英]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. 0
和7
是int
字面量。 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 int
或unsigned 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 int
或unsigned 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.