title: Clamping short to unsigned char
body: <p>I have a simple C function as follows:</p>
  
  <pre><code>unsigned char clamp(short value){
      if (value &lt; 0) return 0;
      if (value &gt; 0xff) return 0xff;
      return value;
  }
  </code></pre>
  
  <p>Is it possible to rewrite it without using any if / else branching while being efficient?</p>
  
  <p>EDIT:</p>
  
  <p>I basically wish to see if some bitwise arithmetic based implementation of clamping is possible. Objective is to process images on GPU (Graphics Processing Unit). This type of code will run on each pixel. I guess that if branches can be avoided, then overall throughput over the GPU would be higher. </p>
  
  <p>A solution like  (value &lt;0? 0 : ((value > 255) ? 255 : value) ) is simply a rehash of if/else branching with syntactic sugar. So I am not looking for it. </p>
  
  <p>EDIT 2:</p>
  
  <p>I can cut it down to a single if as follows but I am not able to think better:</p>
  
  <pre><code>unsigned char clamp(short value){
      int more = value &gt;&gt; 8;
      if(more){
          int sign = !(more &gt;&gt; 7);
          return sign * 0xff;
      }
      return value;
  }
  </code></pre>
  
  <p>EDIT 3:</p>
  
  <p>Just saw a very nice implementation of this in FFmpeg code: </p>
  
  <pre><code>/**
   * Clip a signed integer value into the 0-255 range.
   * @param a value to clip
   * @return clipped value
   */
  static av_always_inline av_const uint8_t av_clip_uint8_c(int a)
  {
      if (a&amp;(~0xFF)) return (-a)&gt;&gt;31;
      else           return a;
  }
  </code></pre>
  
  <p>This certainly works and reduces it to one if nicely. </p>