title: Signed right shift = strange result?
body: <p>I was helping someone with their homework and ran into this strange issue. The problem is to write a function that reverses the order of bytes of a signed integer(That's how the function was specified anyway), and this is the solution I came up with:</p>
  
  <pre><code>int reverse(int x)
  {
      int reversed = 0;
  
      reversed = (x &amp; (0xFF &lt;&lt; 24)) &gt;&gt; 24;
      reversed |= (x &amp; (0xFF &lt;&lt; 16)) &gt;&gt; 8;
      reversed |= (x &amp; (0xFF &lt;&lt; 8)) &lt;&lt; 8;
      reversed |= (x &amp; 0xFF) &lt;&lt; 24;
  
      return reversed;
  }
  </code></pre>
  
  <p>If you pass <code>0xFF000000</code> to this function, the first assignment will result in <code>0xFFFFFFFF</code>. I don't really understand what is going on, but I know it has something to do with conversions back and forth between signed and unsigned, or something like that.</p>
  
  <p>If I either append <code>ul</code> to <code>0xFF</code> it works fine, which I assume is because it's forced to unsigned then converted to signed or something in that direction. The resulting code also changes; without the <code>ul</code> specifier it uses sar(shift arithmetic right), but as unsigned it uses shr as intended.</p>
  
  <p>I would really appreciate it if someone could shed some light on this for me. I'm supposed to know this stuff, and I thought I did, but I'm really not sure what's going on here.</p>
  
  <p>Thanks in advance!</p>