Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The problem with most answers to this question is portability. I've provided a portable answer <a href="https://stackoverflow.com/questions/15529994/most-efficient-way-to-store-an-unsigned-16-bit-integer-to-a-file/15532021">here</a>, but this recieved relatively little positive feedback. Note that C defines undefined behavior as: behavior, upon use of a nonportable or erroneous program construct or of <em>erroneous data</em>, for which this International Standard imposes no requirements.</p> <p>The answer I'll give here won't assume that <code>int</code> is 16 bits in width; It'll give you an idea of how to represent "larger int" values. It's the same concept, but uses a dynamic loop rather than two <code>fputc</code>s.</p> <p>Declare an array of <code>sizeof int</code> unsigned chars: <code>unsigned char big_endian[sizeof int];</code></p> <p>Separate the sign and the absolute value.</p> <pre><code>int sign = value &lt; 0; value = sign ? -value : value; </code></pre> <p>Loop from <code>sizeof int</code> to 0, writing the least significant bytes:</p> <pre><code>size_t foo = sizeof int; do { big_endian[--foo] = value % (UCHAR_MAX + 1); value /= (UCHAR_MAX + 1); } while (foo &gt; 0); </code></pre> <p>Now insert the sign: <code>foo[0] |= sign &lt;&lt; (CHAR_BIT - 1);</code></p> <p>Simple, yeh? Little endian is equally simple. Just reverse the order of the loop to go from 0 to <code>sizeof int</code>, instead of from <code>sizeof int</code> to 0:</p> <pre><code>size_t foo = 0; do { big_endian[foo++] = value % (UCHAR_MAX + 1); value /= (UCHAR_MAX + 1); } while (foo &lt; sizeof int); </code></pre> <p>The portable methods make more sense, because they're well defined.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload