gpt4 book ai didi

c++ - 将无符号字符按位左移 16 是什么意思

转载 作者:IT老高 更新时间:2023-10-28 22:58:58 25 4
gpt4 key购买 nike

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

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

最佳答案

当你移动一个值时,

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

如果 unsigned char 适合 int,则 x 的类型被提升为 int(大多数系统) , 或 unsigned 如果 unsigned char 不适合 int (罕见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 段:按位移位运算符

The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand.

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

If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions.

脚注:

1:已知某些 DSP 芯片以及某些 Cray super 计算机具有 sizeof(char) == sizeof(int)。这以增加内存消耗为代价简化了处理器的加载存储单元的设计。

2:如果你的左移提升为int,然后溢出int,这是未定义的行为(恶魔可能会飞出你的 Nose )。相比之下,unsigned 的溢出始终是明确定义的,因此位移应该通常在 unsigned 类型上完成。

关于c++ - 将无符号字符按位左移 16 是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10748506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com