按位补运算 [英] Bitwise complement operator
问题描述
你们可以解释一下下面的程序
Can you guys please explain the below program
int main()
{
int max = ~0;
printf("%d\n",max);
return 0;
}
据我所知〜会翻转位。在这种情况下,即0〜将设置所有位为1,那么最大变量应该包含MAX的价值,但我得到O / P为-1。因此,可以在这里任何人都请告诉我为什么我收到O / P为-1。
AFAIK ~ will flip the bits. In this case i.e ~0 will set all the bits into 1. So max variable should contain MAX value but I am getting o/p as -1. So can anyone here please tell me why I am getting o/p as -1.
推荐答案
为什么你期望获得最大值?在二进制补码重新签订presentation全1位模式代表 1
。这只是事情是这样的。
Why did you expect to obtain the "max value"? In 2's-complement signed representation all-1 bit pattern stands for -1
. It is just the way it is.
在二进制补码的最大值重新签订presentation重新由 01111 ... 1
psented $ P $位模式(即第一位为 0
)。你得到了什么是 1111 ... 1
,这显然是否定的,因为第一个位 - 符号位 - 为 1
。
Maximum value in 2's-complement signed representation is represented by 01111...1
bit pattern (i.e the first bit is 0
). What you got is 1111...1
, which is obviously negative since the very first bit - sign bit - is 1
.
如果你想在这里补充为零产生最大值,用一个例子的符号的再presentation
If you want an example where complemented zero produces a "max value", use unsigned representation
int main() {
unsigned max = ~0u;
printf("%u\n", max);
}
这篇关于按位补运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!