Do not assume that a right shift operation is implemented as either an arithmetic (signed) shift or a logical (unsigned) shift. If E1
in the expression E1 >> E2
has a signed type and a negative value, the resulting value is implementation defined and may be either an arithmetic shift or a logical shift. Also, be careful to avoid undefined behavior while performing a bitwise shift []
For implementations in which an arithmetic shift is performed, and the sign bit can be propagated as the number is shifted.
int stringify; char buf[sizeof("256")]; sprintf(buf, "%u", stringify >> 24);
If stringify
has the value 0x80000000
, stringify >> 24
evaluates to 0xFFFFFF80
and the subsequent call to sprintf()
results in a buffer overflow.
For bit extraction, one remediation is to use the idiom ((number >> 24) & 0xff).