title: What is the standard compliant way to convert a signed integral value to a sortable, unsigned in C++?
body: <p>I have a use case where I need to convert signed values to unsigned, to make values sortable.  I need this for <code>char</code>, <code>short</code>, <code>int</code>, <code>long</code>, and <code>long long</code></p>
  
  <p>By sortable, I mean that for <code>signed</code> type X, if <code>(a &lt; b)</code> then converting to unsigned the <code>converted(a) &lt; converted(b)</code>.   Note that in many cases, converting from a negative <code>signed</code> value directly to a <code>unsigned</code> value will make the value greater than <code>0</code> and breaks this constraint (<em>two's complement implementations</em>)</p>
  
  <p>The simplest idea for a <code>char</code> is:</p>
  
  <pre><code>unsigned char convert(char x)
  {
         return (unsigned char)(x ^ 0x80);  // flip sign to make it sortable
  }
  </code></pre>
  
  <p>But this seems to be <code>undefined behavior</code>.</p>
  
  <p>While it might be possible to convert to a larger type, add the types MIN value, and convert to the <code>unsigned</code> type, I'm not sure this is any more compliant, and won't work with <code>long long</code></p>
  
  <p>How can this be done without any <code>undefined behavior</code> for all types?</p>
  
  <p>It seems safe to convert using <code>memcpy</code>, but it's not clear how to maintain sort order in a compliant way.</p>
  
  <p>(Note that this is similar to: <a href="https://stackoverflow.com/questions/9467475/no-compliant-way-to-convert-signed-unsigned-of-same-size">No compliant way to convert signed/unsigned of same size</a> except I need the results to be maintain sort order)</p>