...
This compliant solution eliminates the possibility of undefined behavior resulting from a left shift operation on integers, it also uses unsigned integers in accordance with INT13-A. Use bitwise operators only on unsigned operands. Smaller sized integers are promoted according to the integer promotion rules (see INT02-AC. Understand integer conversion rules).
| Code Block | ||
|---|---|---|
| ||
unsigned int ui1, ui2, sresult;
if ((ui2 >= sizeof(int)*CHAR_BIT)
|| (ui1 > (INT_MAX >> ui2)) )
{
/* handle error condition */
}
else {
sresult = ui1 << ui2;
}
|
...