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;
When you shift a value,
The type of
xis promoted tointifunsigned charfits in anint(most systems), or tounsignedifunsigned chardoes not fit in anint(rare1). As long as yourintis 25 bits wide or wider, then no data will be discarded2.Note that this is completely unrelated to the fact that
16has typeint.Source: from n1516 (C99 draft):
§6.5.7 paragraph 3: Bitwise Shift Operators
§6.3.1.1 paragraph 2: Boolean, characters, and integers
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
intand then overflows theint, this is undefined behavior (demons may fly out your nose). By comparison, overflowing anunsignedis always well-defined, so bit shifts should usually be done onunsignedtypes.