相似程序中的位移不同结果
这是一个程序
#include<stdio.h>
#include<stdlib.h>
int main()
{
unsigned char a=0x80;
printf("%d\n",a<<1);
}
上面的输出是256
现在这是上述程序的另一个版本
#include<stdio.h>
#include<stdlib.h>
int main()
{
unsigned char a=0x80;
a=a<<1;
printf("%d\n",a);
}
上面的输出是
0
据我的理解,我看不出两者之间有什么区别? 即为什么第一个程序中的输出为 256 而第二个程序中的输出为 0 两者的语句有什么区别?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在您的平台上,
unsigned char
只有 8 位宽,因此a <<当您将 1 分配回窄
会将 1 从左端移出。另一方面,在a
时,1printf
调用中,a
首先被提升为整数(在您的平台上比 8 位宽),因此该位保留下来。On your platform,
unsigned char
is only 8 bits wide, soa << 1
shifts the 1 out the left end when you assign it back to the narrowa
. In theprintf
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.表达式
a <<根据 C 语言的类型提升规则,1
属于int
类型。在第一个程序中,您将获取这个int
(现在其值为0x100
),并将其直接传递给printf()
,这样就可以工作了正如预期的那样。在第二个程序中,您的
int
被分配给unsigned char
,这会导致0x100
截断为0x00
。The expression
a << 1
is of typeint
according to the C language's type-promotion rules. In the first program, you are taking thisint
, which now has the value0x100
, and passing it directly toprintf()
, which works as expected.In the second program, your
int
is assigned to anunsigned char
, which results in truncation of0x100
to0x00
.<<
将结果提升为(无符号)int
,但在第二个示例中,您将其强制返回为(无符号)char
> 溢出回到 0。<<
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.在第二种情况下,
a
只有8位长,0x80 << 1
是0x100
然后转换为 char 剪辑顶部位,因此变为0x00
当直接在
printf
语句中时,它看起来对于int
所以它不会剪辑它......In the second case,
a
is only 8 bit long,0x80 << 1
is0x100
then cast to a char clips the top bit so becomes0x00
When directly in the
printf
statement, it is looking for anint
so it won't clip it...