Registered User
Registered User

Reputation: 5361

bit shift different result in similar programs

Here is one program

#include<stdio.h>
#include<stdlib.h>
int main()
{
 unsigned char a=0x80;
 printf("%d\n",a<<1);
}

The output of above is 256 Now here is one more version of above program

#include<stdio.h>
#include<stdlib.h>
int main()
{
 unsigned char a=0x80;
  a=a<<1;
 printf("%d\n",a);
}

The output of above is

0

As far as my understanding is I am not able to see any difference between the two? i.e. why is output coming 256 in first one and 0 in second program what is the difference in statements in both?

Upvotes: 2

Views: 143

Answers (4)

Blindy
Blindy

Reputation: 67380

<< promotes the result to an (unsigned) int, but in the second example, you force it back into an (unsigned) char where it overflows back to 0.

Upvotes: 2

JSBձոգչ
JSBձոգչ

Reputation: 41378

The expression a << 1 is of type int according to the C language's type-promotion rules. In the first program, you are taking this int, which now has the value 0x100, and passing it directly to printf(), which works as expected.

In the second program, your int is assigned to an unsigned char, which results in truncation of 0x100 to 0x00.

Upvotes: 5

Matthieu
Matthieu

Reputation: 16397

In the second case, a is only 8 bit long, 0x80 << 1 is 0x100 then cast to a char clips the top bit so becomes 0x00

When directly in the printf statement, it is looking for an int so it won't clip it...

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477040

On your platform, unsigned char is only 8 bits wide, so a << 1 shifts the 1 out the left end when you assign it back to the narrow a. In the printf call, on the other hand, a is first promoted to an integer (which is wider than 8 bits on your platform) and thus the bit survives.

Upvotes: 10

Related Questions