本文介绍了什么意思是按位左移一个unsigned char与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 (稀有)。只要 int 为25位宽或更宽,则不会丢弃任何数据。

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 (rare). As long as your int is 25 bits wide or wider, then no data will be discarded.

注意,这与 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

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

§6.3.1.1 paragraph 2: Boolean, characters, and integers

脚注:

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

: 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.

:如果你的左移被提升到 int 然后溢出 int ,这是未定义的行为(恶魔可能飞出你的鼻子)。通过比较,溢出 unsigned 始终是很好定义的,因此位移位通常应该在 unsigned 类型。

: 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 08:37