title: How to implement arithmetic right shift in C
body: <p>Many lossless algorithms in signal processing require an evaluation of the expression of the form ⌊&nbsp;<em>a</em>&nbsp;/&nbsp;2<sup><em>b</em></sup>&nbsp;⌋, where <em>a</em>, <em>b</em> are signed (<em>a</em> possibly negative, <em>b</em> non-negative) integers and ⌊·⌋ is the floor function. This usually leads to the following implementation.</p>
  
  <pre><code>int floor_div_pow2(int numerator, int log2_denominator)
  {
      return numerator &gt;&gt; log2_denominator;
  }
  </code></pre>
  
  <p>Unfortunately, the C standard states that the result of the <code>&gt;&gt;</code> operator is implementation-defined if the left operand has a signed type and a negative value.</p>
  
  <p>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 <code>numerator</code> is <code>INT_MIN</code>.)</p>
  
  <p>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 code<sup>1</sup> as the code fragment above while avoiding the implementation-defined behaviour.</p>
  
  <p><sup>1</sup> considering, e.g., gcc and x86-64 platform</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>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 ⌊&nbsp;<em>a</em>&nbsp;/&nbsp;2<sup><em>b</em></sup>&nbsp;⌋ in a portable way.</p>