在C左移(炭)0xFF的8和投它为int [英] In C Left shift (char) 0xFF by 8 and cast it to int
问题描述
在的(字符)左移0xFF的8和铸造它诠释我们得到-256或0xffffff00。
有人可以解释为什么发生这种情况?
的#include<&stdio.h中GT;
INT主要(无效)
{
焦C = 0xFF的;
输出(%d个%×\\ N,(int)的(℃下;&下; 8),(INT)(℃下;&下; 8));
返回0;
}
输出为
-256 FFFFFF00
字符
可符号或无符号 - 它的实现定义。你看到这些结果,因为字符
默认情况下,在你的编译器签名。
有关的符号字符0xFF的对应于-1(这是怎么补工作)。当您尝试移动它,它首先被提升到 INT
,然后转向 - 你有效地得到256乘以
因此,它是这个code:
的char c = 0xFF的; // -1
INT偏移=℃下;&下; 8; // - 256(-1 * 256)
的printf(%D,%X,转移,转移);
On left shift of (char) 0xff by 8 and casting it to int we get -256 or 0xffffff00. Can somebody explain why this should happen?
#include <stdio.h>
int main (void)
{
char c = 0xff;
printf("%d %x\n", (int)(c<<8),(int)(c<<8));
return 0;
}
Output is
-256 ffffff00
char
can be signed or unsigned - it's implementation-defined. You see these results because char
is signed by default on your compiler.
For the signed char 0xFF corresponds to −1 (that's how two's complement work). When you try to shift it it is first promoted to an int
and then shifted - you effectively get multiplication by 256.
So it is this code:
char c = 0xFF; // -1
int shifted = c << 8; //-256 (-1 * 256)
printf( "%d, %x", shifted, shifted );
这篇关于在C左移(炭)0xFF的8和投它为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!