Let's say we have the following code, meant to shift the bits of a
to the left by i
and replace the i
LSBs of a
with the i
MSBs of b
unsigned short a;
unsigned short b;
auto i = 4;
a = (a << i) | (b >> (16 - i));
This works as expected. Now, let's consider the situation where we want to be able to do this for pairs of different types. i.e. we want to shift the bits of a
to the left by i
and replace the i
LSBs of a
with the i
MSBs of b
, except now we have no guarantee on the size of a
and b
, only that they are unsigned. Let's consider the case where the size of a
is less than that of b
unsigned short a;
unsigned int b;
auto i = 4;
a = (a << i) | (b >> (32- i));
I'm worried about "overshifting" a
. However, depending on when the promotion of a
to unsigned int
occurs, a value may or may not be an overshift. Consider a value of i=24
. This would cause undefined behavior if the type conversion happens after the shift, however not before. Thus, my question is when type conversion in this case will occur? I suppose I could explicitly cast a
to the larger type, but I'd like to avoid that if possible.