title: How does one safely static_cast between unsigned int and int?
body: <p>I have an 8-character <code>string</code> representing a hexadecimal number and I need to convert it to an <code>int</code>.  This conversion has to preserve the bit pattern for strings <code>"80000000"</code> and higher, i.e., those numbers should come out negative.  Unfortunately, the naive solution:</p>
  
  <pre><code>int hex_str_to_int(const string hexStr)
  {    
      stringstream strm;
      strm &lt;&lt; hex &lt;&lt; hexStr;
      unsigned int val = 0;
      strm &gt;&gt; val;
      return static_cast&lt;int&gt;(val);
  }
  </code></pre>
  
  <p>doesn't work for my compiler if <code>val &gt; MAX_INT</code> (the returned value is 0).  Changing the type of val to <code>int</code> also results in a 0 for the larger numbers.  I've tried several different solutions from various answers here on SO and haven't been successful yet.</p>
  
  <p>Here's what I do know:</p>
  
  <ul>
  <li>I'm using HP's C++ compiler on OpenVMS (using, I believe, an Itanium processor).</li>
  <li><code>sizeof(int)</code> will be at least 4 on every architecture my code will run on.</li>
  <li>Casting from a number > INT_MAX to int is implementation-defined. On my machine, it usually results in a 0 but interestingly casting from <code>long</code> to <code>int</code> results in <code>INT_MAX</code> when the value is too big.</li>
  </ul>
  
  <p>This is surprisingly difficult to do correctly, or at least it has been for me.  Does anyone know of a <strong>portable</strong> solution to this?</p>
  
  <p><strong>Update:</strong></p>
  
  <p>Changing <code>static_cast</code> to <code>reinterpret_cast</code> results in a compiler error.  A comment prompted me to try a C-style cast: <code>return (int)val</code> in the code above, and it worked.  <em>On this machine.</em>  Will that still be safe on other architectures?</p>