开发者

bit shift different result in similar programs

Here is one program

#include<stdio.h>
#include<stdlib.h>
int main()
{
 un开发者_运维问答signed 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?


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.


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.


<< 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.


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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜