按位左移一个带有 16 的无符号字符是什么意思

what does it mean to bitwise left shift an unsigned char with 16

本文关键字:无符号 字符 意思 是什么 一个 左移      更新时间:2023-10-16

我正在读取一个包含unsigned char变量的.cpp文件,它正在尝试按位左移 16 位,因为unsigned char由 8 位组成,左移 16 位将擦除所有位并用八个 0 填充它。

unsigned char byte=0xff; byte << 16;

当你移动一个值时,

unsigned char x = ...;
int y = x << 16;

如果unsigned char适合某个int(大多数系统),则x类型提升为 int,如果不适合int,则unsigned char提升为 unsigned(罕见1)。 只要您的int宽度为 25 位或更宽,就不会丢弃任何数据2.

请注意,这与16具有int类型的事实完全无关。

/* All three are exactly equivalent */
x << 16;
x << 16u;
x << (unsigned char) 16;

来源:来自n1516(C99草案):

§6.5.7 第3段:按位移位运算符

对每个操作数执行整数提升。结果的类型为 提升的左操作数。

§6.3.1.1 第2段:布尔值、字符和整数

如果 int 可以表示原始类型的所有值(受宽度限制,对于 位字段),该值转换为 int;否则,它将转换为无符号 国际。这些称为整数促销。

脚注:

1:已知某些DSP芯片以及某些Cray超级计算机具有sizeof(char) == sizeof(int)。 这简化了处理器负载存储单元的设计,但代价是额外的内存消耗。

2:如果你的左移被提升到int,然后溢出int,这是不确定的行为(恶魔可能会飞出你的鼻子)。 相比之下,溢出unsigned总是明确定义的,因此通常应该unsigned类型进行位移。

如果char适合int,它将被提升为int,结果将如您所料。如果不是这种情况,则根据标准,它是未定义的行为,并且可能会发出编译警告。从标准:

The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.