简体   繁体   English

char类型按位操作失败到int

[英]char type bitwise operation fails in to int

I am try to bitwise operate in C. Here is my code: 我尝试在C中按位操作。这是我的代码:

int main() {
    char c = 127;
    c <<= 1;
    if (c == 0xfe) {
        printf("yes");
    }
    else {
        printf("No");
    }
    return 0;
}

System console print No. What I expect to receive is Yes. 系统控制台打印否。我希望收到的是是。 the value in c after bit moving is ffffffffe. 位移后c中的值为ffffffffe。 It seems that system has changed 8bits to a 32bits. 似乎系统已经将8位改为32位。 Can anyone help me. 谁能帮我。

You have correctly figured out the content of the lower byte, ie 0xfe . 您已正确计算出低位字节的内容,即0xfe However, there is more to what's actually happening here: when you write 然而,在这里发生的事情还有更多:当你写作时

if (c == 0xfe) {
    ...
}

you are comparing c , a char , to an int constant 0xfe . 你正在将c ,一个char与一个int常量0xfe In this situation C rules require promoting char c to int for comparison. 在这种情况下,C规则要求 char c提升为int以进行比较。 Since char is signed on your platform, 0xfe gets promoted to 0xfffffffe , which is why the comparison subsequently fails. 由于char在您的平台上签名,因此0xfe被提升为0xfffffffe ,这就是比较随后失败的原因。

If you want to do the comparison in char type, cast 0xfe to char , like this: 如果你想在char类型中进行比较, 0xfechar ,如下所示:

if (c == (char)0xfe) {
    ...
}

Demo 1. 演示1。

Unsigned characters, on the other hand, would give you no trouble with int promotion, because they fit nicely in an int : 另一方面,无符号字符会给你int促销带来麻烦,因为它们非常适合int

unsigned char c = 127;
c<<=1;
if (c == 0xfe) { // No casting is necessary
    ...
}

Demo 2. 演示2。

Note: The behavior of c <<= 1 is implementation-defined due to char overflow. 注意:由于char溢出, c <<= 1的行为是实现定义的。

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

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