Char Bitwise operation type not executed for int

I am trying bitwise control in C. Here is my code:

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

System console What I expect to receive is Yes. the value in c after moving the bit is ffffffffe. It seems that the system has changed 8 bits to 32 bits. Can someone help me.

+4
source share
1 answer

You correctly parsed the contents of the low byte, i.e. 0xfe. However, there is more to what actually happens here: when you write

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

c, a char int 0xfe. C char c int . char, 0xfe 0xfffffffe, .

char, 0xfe char, :

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

1.

, , int, int:

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

2.

. c <<= 1 - char.

+7

Source: https://habr.com/ru/post/1694311/


All Articles