title: C convert signed to unsigned maintaining exact bits
body: <p><strong>Edit:</strong> I updated the example to be C. I am concerned specifically with C and not C++ (sorry for the confusion, see situation below).</p>
  
  <p>I am looking for a safe way to convert a signed integer to an unsigned integer while always maintaining the exact same bit pattern between conversions. As I understand it, simply casting has undefined or implementation dependent behavior so it is not safe to rely on (case A below). But what about bit-wise operators like OR (case B below)? Can bit-wise OR be used to safely convert signed to unsigned? What about the reverse?</p>
  
  <p>Example:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  int main() {
      // NOTE: assuming 32bit ints
      // example bit pattern: 11111111110001110001001111011010
      //   signed int value: -3730470
      // unsigned int value: 4291236826
  
      // example 1
      // signed -&gt; unsigned
      int s1 = -3730470; 
      unsigned int u1a = (unsigned int)s1;
      unsigned int u1b = (unsigned int)0 | s1;
  
      printf("%u\n%u\n", u1a, u1b);
  
      // example 2
      // unsigned -&gt; signed
      unsigned int u2 = 4291236826;
      int s2a = (int)u2;
      int s2b = (int)0 | u2;
  
      printf("%i\n%i\n", s2a, s2b);
  }
  </code></pre>
  
  <hr>
  
  <p><strong>Situation:</strong> I am writing a <a href="https://www.postgresql.org/docs/9.6/static/xfunc-c.html" rel="nofollow noreferrer">PostgreSQL C-Language function</a>/extension to add popcount functionality (<a href="https://github.com/yo1dog/pg_popcount/blob/master/popcount.c" rel="nofollow noreferrer">my first attempt code here</a>). PostgreSQL does not support unsigned types (<a href="https://www.postgresql.org/docs/9.6/static/datatype-numeric.html" rel="nofollow noreferrer">ref</a>). All the efficient methods of calculating popcount I found require unsigned data types to work correctly. Therefore, I must be able to convert the signed data types to an unsigned data type without changing the bit pattern.</p>
  
  <p><strong>Off topic:</strong> I do realize that an alternate solution would be to use PostgreSQL bit string <code>bit</code> and <code>varbit</code> data types instead of the integer data types, but for my purposes the integer data types are much easier to use and manage.</p>