mihsathe
mihsathe

Reputation: 9154

C bitwise shift

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

Upvotes: 2

Views: 1967

Answers (3)

ironMover
ironMover

Reputation: 107

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.

Upvotes: 1

Mysticial
Mysticial

Reputation: 471569

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.

Upvotes: 12

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799430

Because what you describe is a rotate, not a shift. 0 is always shifted in on left shifts.

Upvotes: 0

Related Questions