什么意思是按位左移一个unsigned char与16 [英] what does it mean to bitwise left shift an unsigned char with 16
问题描述
我正在读一个包含 unsigned char
变量的.cpp文件,它尝试按位左移16位,因为 unsigned char
由8位组成,左移16位将擦除所有位并用8个0填充。
i am reading a .cpp file containing a unsigned char
variable, it's trying the bitwise left shift 16 bits, since an unsigned char
is composed of 8 bits, left shift 16 bits will erase all the bits and fill it with eight 0s.
unsigned char byte = 0xff;字节<< 16;
unsigned char byte=0xff; byte << 16;
推荐答案
移动值时,
unsigned char x = ...;
int y = x << 16;
x
的类型提升为 int 如果
unsigned char
符合 int
,或 unsigned
如果 unsigned char
不适合 int
(稀有 1 )。只要 int
为25位宽或更宽,则不会丢弃任何数据 2 。
The type of x
is promoted to int
if unsigned char
fits in an int
(most systems), or to unsigned
if unsigned char
does not fit in an int
(rare1). As long as your int
is 25 bits wide or wider, then no data will be discarded2.
注意,这与 16
有类型 int
的事实完全无关。
Note that this is completely unrelated to the fact that 16
has type int
.
/* All three are exactly equivalent */
x << 16;
x << 16u;
x << (unsigned char) 16;
来源: from n1516(C99 draft):
Source: from n1516 (C99 draft):
§6.5.7第3段:按位移位运算符
§6.5.7 paragraph 3: Bitwise Shift Operators
操作数。
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段:布尔值,字符,和整数
§6.3.1.1 paragraph 2: Boolean, characters, and integers
如果int可以表示原始类型的所有值(由宽度限制,对于
位-field),将该值转换为int;否则,它将转换为unsigned
int。这些称为整数促销。
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超级计算机已知具有 sizeof(char)== sizeof(int)
。这会以额外的内存消耗为代价简化处理器的加载 - 存储单元的设计。
1: Some DSP chips as well as certain Cray supercomputers are known to have sizeof(char) == sizeof(int)
. This simplifies design of the processor's load-store unit at the cost of additional memory consumption.
2 :如果你的左移被提升到 int
然后溢出 int
,这是未定义的行为(恶魔可能飞出你的鼻子)。通过比较,溢出 unsigned
始终是很好定义的,因此位移位通常应该在 unsigned
类型。
2: If your left shift is promoted to int
and then overflows the int
, this is undefined behavior (demons may fly out your nose). By comparison, overflowing an unsigned
is always well-defined, so bit shifts should usually be done on unsigned
types.
这篇关于什么意思是按位左移一个unsigned char与16的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!