I suppose sizeof(char) is one byte. Then when I write following code,
#include<stdio.h>
int main(void)
{
char x = 10;
printf("%d", x<<5);
}
The output is 320
My question is, if char is one byte long and value is 10, it should be:
0000 1010
When I shift by 5, shouldn’t it become:
0100 0001
so why is output 320 and not 65?
I am using gcc on Linux and checked that sizeof(char) = 1
In C, all intermediates that are smaller than
intare automatically promoted toint.Therefore, your
charis being promoted to larger than 8 bits.So your
0000 1010is being shifted up by 5 bits to get 320. (nothing is shifted off the top)If you want to rotate, you need to do two shifts and a mask:
It’s possible to do it faster using inline assembly or if the compiler supports it, intrinsics.