Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C bitwise shift

Tags:

c

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

like image 667
mihsathe Avatar asked Aug 26 '26 08:08

mihsathe


2 Answers

In C, all intermediates that are smaller than int are automatically promoted to int. Therefore, your char is being promoted to larger than 8 bits.

So your 0000 1010 is 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:

unsigned char x = 10;

x = (x << 5) | (x >> 3);
x &= 0xff;

printf("%d", x);

It's possible to do it faster using inline assembly or if the compiler supports it, intrinsics.

like image 75
Mysticial Avatar answered Aug 28 '26 00:08

Mysticial


Mysticial is right. If you do

char x = 10;
printf("%c", x);

It prints "@", which, if you check your ASCII table, is 64.

0000 1010 << 5 = 0001 0100 0000

You had overflow, but since it was promoted to an int, it just printed the number.

like image 43
ironMover Avatar answered Aug 27 '26 23:08

ironMover