简体   繁体   English

类型转换

[英]Typecasting Inversion

I really do not understand why I have to typecast the variable b after inversion (unary operator ~ ). 我真的不明白为什么我必须在反演后对变量b进行类型转换(一元运算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. ~b结果是提升类型int (通常是b与任何其他一元运算符的结果+-~ )所以你需要对结果进行类型转换。

From C11 spec draft section 6.5.3.3 Unary arithmetic operator: 来自C11规范草案第6.5.3.3节一元算术运算符:

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 . 如果提升类型是无符号类型 ,则表达式~E等于该类型中可表示最大值减去E.

So, 所以,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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