Note that there are some explanatory texts on larger screens.

plurals
  1. POData serialization in C?
    primarykey
    data
    text
    <p>I have this structure which I want to write to a file:</p> <pre><code>typedef struct { char* egg; unsigned long sausage; long bacon; double spam; } order; </code></pre> <p>This file must be binary and must be readable by any machine that has a C99 compiler.</p> <p>I looked at various approaches to this matter such as ASN.1, XDR, XML, ProtocolBuffers and many others, but none of them fit my requirements:</p> <ul> <li>small</li> <li>simple</li> <li>written in <strong>C</strong></li> </ul> <p>I decided then to make my own data protocol. I could handle the following representations of <strong>integer</strong> types:</p> <ul> <li>unsigned</li> <li>signed in <em>one's complement</em></li> <li>signed in <em>two's complement</em></li> <li>signed in <em>sign and magnitude</em></li> </ul> <p>in a valid, simple and clean way (impressive, no?). However, the <strong>real</strong> types are being a pain now.</p> <p>How should I read <code>float</code> and <code>double</code> from a byte stream? The standard says that bitwise operators (at least <code>&amp;</code>, <code>|</code>, <code>&lt;&lt;</code> and <code>&gt;&gt;</code>) are for <strong>integer</strong> types only, which left me without hope. The only way I could think was:</p> <pre><code>int sign; int exponent; unsigned long mantissa; order my_order; sign = read_sign(); exponent = read_exponent(); mantissa = read_mantissa(); my_order.spam = sign * mantissa * pow(10, exponent); </code></pre> <p>but that doesn't seem really efficient. I also could not find a description of the representation of <code>double</code> and <code>float</code>. How should one proceed before this?</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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