在 C 中左移 (char) 0xFF 8 并将其转换为 int [英] In C Left shift (char) 0xFF by 8 and cast it to int
问题描述
在 (char) 0xff 左移 8 并将其转换为 int 时,我们得到 -256 或 0xffffff00.有人可以解释为什么会发生这种情况吗?
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
", (int)(c<<8),(int)(c<<8));
return 0;
}
输出是
-256 ffffff00
推荐答案
char
可以是有符号或无符号的——它是由实现定义的.您会看到这些结果,因为 char
在您的编译器上默认已签名.
char
can be signed or unsigned - it's implementation-defined. You see these results because char
is signed by default on your compiler.
对于有符号字符,0xFF 对应于 -1(这就是二进制补码的工作方式).当您尝试对其进行移位时,它首先被提升为 int
然后移位 - 您实际上得到了乘以 256.
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.
原来是这样的代码:
char c = 0xFF; // -1
int shifted = c << 8; //-256 (-1 * 256)
printf( "%d, %x", shifted, shifted );
这篇关于在 C 中左移 (char) 0xFF 8 并将其转换为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!