Many lossless algorithms in signal processing require an evaluation of the expression of the form ⌊ a / 2b ⌋, where a, b are signed (a possibly negative, b non-negative) integers and ⌊·⌋ is the floor function. This usually leads to the following implementation.

int floor_div_pow2(int numerator, int log2_denominator) { return numerator >> log2_denominator; }

Unfortunately, the C standard states that the result of the >> operator is implementation-defined if the left operand has a signed type and a negative value.

To ensure the correct behaviour on all platforms, one could replace this simple function with multiple if-else conditions, resulting in poor program performance. (One must to treat an overflow of an integer and consider the case when the numerator is INT_MIN .)

Therefore I ask, what is the best practice for implementation of the arithmetic right shift in C? Ideally, I'm looking for the construct that compiles into the same code1 as the code fragment above while avoiding the implementation-defined behaviour.

1 considering, e.g., gcc and x86-64 platform

UPDATE:

After some thought, I realized that I made an incorrect implication in the above question. Computing the floor function for negative numbers using an arithmetic shift doesn't make sense if the platform doesn't use two's complement. The goal is to implement the expression ⌊ a / 2b ⌋ in a portable way.