无符号字符的按位求反 [英] Bitwise negation of unsigned char
问题描述
这是一个与c99标准相关的问题,涉及整数提升和未签名字符的按位求反.
This is a question relating the c99 standard and concerns integer promotions and bitwise negations of unsigned char.
在6.5.3.3节中指出:
In section 6.5.3.3 it states that:
对操作数执行整数提升,结果 具有提升的类型.如果提升的类型是无符号类型,则 表达式〜E等于其中可表示的最大值 输入减号E.
The integer promotions are performed on the operand, and the result has the promoted type. If the promoted type is an unsigned type, the expression ~E is equivalent to the maximum value representable in that type minus E.
我说的那句话我理解正确吗?
Am I understanding that correctly when I say that, that means that:
unsigned int ui = ~ (unsigned char) ~0; // ui is now 0xFF00.
我的困惑源于与一位同事的讨论,他在我们的编译器中看到以下行为.
My confusion stems from a discussion with a collegue where he is seeing the following behaviour in our compiler.
unsigned char uc = 0;
unsigned char ucInverted = ~0;
if( ~uc == ~0 ) // True, obviously
if( ~ucInverted == ~(~0) ) // False as it evaluates to: 0xFF00 == 0x0000
if( ~uc == ucInverted ) // False as it evaluates to: 0xFFFF == 0x00FF
if( uc == ~ucInverted ) // False as it evaluates to: 0x0000 == 0xFF00
此行为已通过gcc确认.
This behaviour is confirmed with gcc.
是否有可能获得适当的预期字符比较,以使这些情况中的每一个都为真?
Is it possible to get proper expected char comparisons where each of these cases will evaluate to true?
推荐答案
~uc
的类型为int
(值0xFFFF
). ucInverted
的类型为unsigned char
(值0xFF
),然后提升为int
(值0x00FF
).因此它们是不相等的.
~uc
is of type int
(value 0xFFFF
). ucInverted
is of type unsigned char
(value 0xFF
), which is then promoted to int
(value 0x00FF
). Thus they are not equal.
我想你可以if ((unsigned char)~uc == ucInverted)
.这两个操作数仍将进行提升,但是在提升之前它们将具有相同的值.
I guess you could do if ((unsigned char)~uc == ucInverted)
. Both operands will still undergo promotion, but they will have identical values before the promotion.
这篇关于无符号字符的按位求反的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!