title: Platform independent storage of signed integers
body: <p>I want to write signed integer values into a file in a platform independent way.</p>
  
  <p>If they were unsigned, I would just convert them from host byte order to LE (or BE) with the <a href="http://www.kernel.org/doc/man-pages/online/pages/man3/endian.3.html" rel="nofollow">endian(3)</a> family of functions.</p>
  
  <p>I'm not sure how to deal with signed integers though. If I cast them to unsigned values, I loose the sign, since the C standard does not guarantee that</p>
  
  <pre><code>(int) ((unsigned) -1)) == -1
  </code></pre>
  
  <p>The other option would be to I cast a pointer to the value (i.e., reinterpret the byte sequence as unsigned), but it I'm not convinced that converting endianness after that is going to give anything sensible.</p>
  
  <p>What is the proper way for platform independent signed integer storage?</p>
  
  <p><strong>Update</strong>:</p>
  
  <ul>
  <li><p>I know that <em>in practice</em>, almost all architectures use two-complement representation, so that I can losslessly convert between signed and unsigned integers. However, this is question is meant to be more theoretical.</p></li>
  <li><p>Just rolling out my own integer representation (be that storing the decimal letters as ascii characters, or separately storing the sign bit) is of course a solution. However, I'm interested if there is a way that works without completely abandoning the native binary representation.</p></li>
  </ul>