title: sign function in C using bit operators only
body: <p>I'm trying to implement a sign function using only bitwise operators.  I know that if I just want to extract the sign bit of a signed integer, I can do: <code>(x &gt;&gt; 31) &amp; 1</code>.</p>
  
  <p>Also, I understand that conditionals can be written as boolean expressions:</p>
  
  <p><code>if(x) a=y else a=z</code> which is equivalent to <code>a = x ? y:z</code> can be rewritten as: </p>
  
  <p><code>a=( (x&lt;&lt;31) &lt;&lt; 31 ) &amp; y + ( !x &lt;&lt; 31) &gt;&gt; 31) &amp; z</code>, assuming x=1 or 0.</p>
  
  <p>This problem gets a little tricky though because I have 3 conditional scenarios:<br>
  return 1 if positive, 0 if zero, and -1 if negative.</p>
  
  <p>I was thinking that in order to do this properly, I need to use <code>!</code> operator and the fact that <code>!0x&lt;nonzero #&gt;=0</code>, <code>!0x0=1</code>, <code>!0x1=0</code>.  </p>
  
  <p>So I came up with something like this, which is incorrect:</p>
  
  <pre><code>/*                                                                              
   * sign - return 1 if positive, 0 if zero, and -1 if negative                   
   *  Examples: sign(130) = 1                                                     
   *            sign(-23) = -1                                                    
   *  Legal ops: ! ~ &amp; ^ | + &lt;&lt; &gt;&gt;                                                                          
   */
  int sign(int x) {
      return (x&gt;&gt;31) &amp; -1 ) + ( !( !x &gt;&gt; 31 ) &amp; 1;
  }
  </code></pre>
  
  <p>I think I have all the pieces but just not quite sure how to put them all together.  Any help is appreciated.  </p>
  
  <p>Thank you.</p>