Search code examples
ccharbit

Bitwise operation in character


I am curious about a behavior of bit-wise operator of C on Character.

#include <stdio.h>

int main()
{
    int x = 108;
    x = x<<1;
    printf("%d\n", x);
    char y = 108;
    y = y<<1;
    printf("%d", y);
    //printf("%d", y<<1);

    return 0;
}

Here, if I pass like this, y = y<<1, it's output was -40 and when I print it directly like,

printf("%d", y<<1);

it's output was 216.

How I can simulate it?


Solution

  • Note that there is really no << operation on char types - the operands of << are promoted to (at least) int types, and the result is, similarly, an int.

    So, when you do y = y << 1, you are truncating the int result of the operation to a (signed) char, which leaves the most significant bit (the sign bit) set, so it is interpreted as a negative value.

    However, when you pass y << 1 directly to printf, the resulting int is left unchanged.