what does it mean to bitwise left shift an unsigned char with 16

可紊 提交于 2019-12-21 07:55:58

问题


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; byte << 16;


回答1:


When you shift a value,

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

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.

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;

Source: from n1516 (C99 draft):

§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 paragraph 2: Boolean, characters, and integers

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.

Footnotes:

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




回答2:


If char fits inside int, it will be promoted to an int and the result will be as you expect. If that is not the case it is undefined behavior according to the standard, and will probably emit a compile warning. From the standard:

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.



来源:https://stackoverflow.com/questions/10748506/what-does-it-mean-to-bitwise-left-shift-an-unsigned-char-with-16

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!