Bitwise negation of unsigned char

岁酱吖の 提交于 2019-12-07 12:48:18

问题


This is a question relating the c99 standard and concerns integer promotions and bitwise negations of unsigned char.

In section 6.5.3.3 it states that:

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

This behaviour is confirmed with gcc.

Is it possible to get proper expected char comparisons where each of these cases will evaluate to true?


回答1:


~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.

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.



来源:https://stackoverflow.com/questions/18957203/bitwise-negation-of-unsigned-char

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!