Hallvard B Furuseth said:
Duh, a%16 as pete says.
They are the same if you know, which you sometimes do, that
a is nonnegtive.
You the programmer may know that, but if the compiler cannot determine for
sure that the value is always positive, it has to generate code that can
handle all cases. Since division truncates toward zero, ASR (arithmetic
right shift for division) or bitmask (for modulo) is not a solution, it has
to be corrected for negative values, which can be done through appropriate
bit trickery (on 2s complement architectures ;-).
If you know a can only hold positive values, you can tell the compiler by
casting it as unsigned (how ugly!) or you can use the shift or mask
operations (if the divisor is an explicit power of two).
_Unless_ (negative zero) & 15 can be 15.
I don't think that's possible.
but negative_zero >> 4 invokes UB anyway.
What is not good practice is to make a strict rule out of a general
guideline like "be careful about signed bit operations". Or "avoid
goto".
There is one good thing about right shifting negative values: the result is
implementation defined, not undefined behaviour. You can rely on this
operation having consistent behaviour for a given implementation.