需要对按位非 (~) 运算符进行澄清
假设您有以下 C 代码。
unsigned char a = 1;
printf("%d\n", ~a); // prints -2
printf("%d\n", a); // prints 1
我很惊讶地看到 -2 作为 ~1 转换的结果打印出来:
0000 0001 的相反是 1111 1110。那不是 -2。
我在这里缺少什么?
Suppose you have the following C code.
unsigned char a = 1;
printf("%d\n", ~a); // prints -2
printf("%d\n", a); // prints 1
I am surprised to see -2 printed as a result of ~1 conversion:
The opposite of 0000 0001 is 1111 1110. That is anything but -2.
What am I missing here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它是二进制补码。
在二进制补码表示中,如果数字 x 的最高有效位为 1,则实际值将为 −(~x + 1)。
例如,
这是负数的自然表示,因为
请参阅 http://en.wikipedia.org /wiki/Two%27s_complement 了解详细信息。
顺便说一句,要打印无符号值,请使用
%hhu
或%hhx
格式。请参阅 http://www.ideone.com/YafE3。It is two's complement.
In two's complement representation, if a number x's most significant bit is 1, then the actual value would be −(~x + 1).
For instance,
This is a natural representation of negative numbers, because
See http://en.wikipedia.org/wiki/Two%27s_complement for detail.
BTW, to print an unsigned value, use the
%hhu
or%hhx
format. See http://www.ideone.com/YafE3.%d 代表有符号十进制数,而不是无符号数。因此,您的位模式即使存储在无符号变量中,也会被解释为有符号数。
请参阅此有关有符号数字表示的维基百科条目,以了解位值。特别请参阅二进制补码。
%d stands for signed decimal number, not unsigned. So your bit pattern, even though it is stored in an unsigned variable, is interpreted as a signed number.
See this Wikipedia entry on signed number representations for an understanding of the bit values. In particular see Two's complement.
思考带符号数学的一种(有点幽默的)方式是认识到最高有效位实际上代表了它上面的无数位。因此,在 16 位有符号数中,最高有效位是 32768+65536+131072+262144+...等。即 32768*(1+2+4+8+...) 使用幂级数的标准公式,(1+ X + X^2 + X^3 +...) = 1/(1-X ),我们发现 (1+2+4+8+...) 是 -1,所以所有这些位的总和是 -32768。
One (mildly humorous) way to think of signed maths is to recognize that the most significant bit really represents an infinite number of bits above it. So in a 16-bit signed number, the most significant bit is 32768+65536+131072+262144+...etc. which is 32768*(1+2+4+8+...) Using the standard formula for a power series, (1+ X + X^2 + X^3 +...) = 1/(1-X), one discovers that (1+2+4+8+...) is -1, so the sum of all those bits is -32768.