不是十六进制值 0xffff?
我猜输出应该是“0000”,但它是 ffff 因为 Not of ~ffff->0000 0000 0000 0000
#include<stdio.h>
int main()
{
unsigned int a=0xffff;
~a;
printf("%x\n", a);
return 0;
}
I guess the output should be "0000" but it's ffff as Not of ~ffff->0000 0000 0000 0000
#include<stdio.h>
int main()
{
unsigned int a=0xffff;
~a;
printf("%x\n", a);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您需要将值分配回
a
:即使如此,由于数据类型的大小,输出值可能如下所示:
要使其按预期工作(全 0),请设置初始值
a
的值到UINT_MAX
(来自limits.h
)。这样做会将所有位设置为1
。You need to assign the value back to
a
:Even then, the outputted value can look like this, due to the size of the datatype:
To make it work as expected (all 0s), set the initial value of
a
toUINT_MAX
(fromlimits.h
). Doing so sets all the bits to1
.写入
~a;
没有任何效果。它是一个返回a
的补集的表达式,但不会更改a
本身。您需要
a = ~a;
。Writing
~a;
has no effect. It's an expression which returns the complement ofa
, but doesn't changea
itself.You want
a = ~a;
.正如蒂姆和弗拉德所说,你没有对按位反转做任何事情。
即使将代码更改为
a = ~a;
,也可能不会得到零。这是因为,如果unsigned int
超过 16 位,则会有前导零,在反转后会变成 1。所以我希望你的输出是
甚至
如果你想要16位按位运算,你可以使用
As Tim and Vlad said, you aren't doing anything with the bit-wise inversion.
Even if you change the code to
a = ~a;
, you may not get zero. That's because ifunsigned int
has more than 16 bits, you'll have leading zeros, which become 1's after inversion.So I expect your output to be
or even
If you want 16-bit bitwise operations, you can use
因为你没有给a赋值。你需要 a = ~a;
Because you didn't assign the value to a. You need a = ~a;
~a
本身就是一个返回a
按位补码的语句。您可以将 a 分配给~a
(如 @timcooper 建议的那样),或者您可以~a
by itself is a statement that returns the bitwise complement ofa
. You can either assign a to~a
(as @timcooper suggests), or you can正如其他人已经说过的,您需要使用
a = ~a;
将值分配回 a ,或者直接使用printf("%x\n",~a) 打印结果;
但无论哪种情况,您仍然不会像您期望的那样得到零。~ 运算符将翻转变量中的所有位。由于您很可能处理 32 位整数,因此最终会得到
0xFFFF0000
,因为那些高 16 位将从 0 翻转为 1。As others have already said, you need to either assign the value back into a with
a = ~a;
or print the result directly withprintf("%x\n",~a);
but in either case, you are still not going to get zero as you expect.The ~ operator will flip all the bits in the variable. Since you are most likely dealing with 32-bit integers, you are going to end up with
0xFFFF0000
because those upper 16 bits will be flipped from zero's to one's.