Bitwise operation in character

Viewed 68

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?

2 Answers

y<<1 produces an int. To get -40, you were implicitly casting it to a char. In your printf case, you'll need to do the cast explicitly: (char)(y<<1)

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.

Related