按位左移一个带有 16 的无符号字符是什么意思
what does it mean to bitwise left shift an unsigned char with 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.
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- C++中无符号字符溢出
- 使用无符号字符数组有效存储内存
- 在 std::无符号字符的向量处存储 int 的十六进制表示形式
- 如何在保持其值的同时将 c++ 无符号字符变量转换为 char 变量
- 从 std::vector<无符号字符>切片中提取 int?
- 将无符号字符的向量存储在数组中会给我 std::bad_alloc
- 使用 fopen 打开 .pak 文件并使该文件应用于 const 无符号字符* (C++)
- 库特无符号字符
- 寻找一种更好的方法来表示无符号字符数组
- C++ 无符号字符 *{varName};-> C#
- 如何返回/复制unique_ptr<无符号字符[]>的值?
- 将浮点数转换为无符号字符数组并打印出来
- 在函数中返回无符号字符数组,但不返回指针
- 如何在 C/C++ 中将无符号字符*转换为无符号字符数组?
- 如何返回实际值(在我的例子中是无符号字符数组)而不是来自 C++ 函数的指针?
- 如何将带有十六进制值的 std::string 转换为 std::vector<无符号字符>
- 无符号字符打印其 ASCII 值
- 字符数组到无符号字符 *
- 是否可以在 c++ 中将两位数保存在无符号字符中