这是什么意思按位左移16个无符号的字符 [英] what does it mean to bitwise left shift an unsigned char with 16

查看:935
本文介绍了这是什么意思按位左移16个无符号的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读包含 .cpp文件unsigned char型变量,它试图按位左移16位,因为一个 unsigned char型由8位左移16位将清除所有位和八个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.

无符号字符字节= 0xFF的;字节<< 16;

推荐答案

当你转移的值,

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

类型的X 如果晋升为 INT unsigned char型 INT (大多数系统)配合,或无符号如果 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;

来源:从n1516(C99草案):

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可以重新present原始类型的所有值(由宽度的限制,对于
  位字段),值转换为int;否则,它被转换为一个无符号
  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(字符)==的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 ,这是不确定的行为(魔鬼可能飞出你的鼻子)。相比之下,满溢的无符号总是被明确定义,所以移位的通常可在无符号类型。

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.

这篇关于这是什么意思按位左移16个无符号的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆