简体   繁体   中英

Typecasting Inversion

I really do not understand why I have to typecast the variable b after inversion (unary operator ~ ). Can anybody explain why this is needed?

unsigned char a = 0xFF;
unsigned char b = 0x00; 

return (a == (~b));                //expected to return 1 but 0

...

return (a == (unsigned char)(~b)); //after typecast returns 1 as expected

Result of ~b is of promoted type int (Generally result of b with any other unary operator + , - or ~ ) so you need to typecast the result.

From C11 spec draft section 6.5.3.3 Unary arithmetic operator:

The result of the ~ operator is the bitwise complement of its ( promoted ) operand (that is, each bit in the result is set if and only if the corresponding bit in the converted operand is not set). 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 .

So,

unsigned char b = 0x00;
/* ~b = 0xFFFFFFFF (assuming 4 byte int), (unsigned char)~b = 0xFF */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM