Re: Structure size and binary format




"gamehack" <gamehack@xxxxxxxxx> wrote
>
> I've been wondering when I write a structure like:
>
> struct {
> int a;
> unsigned int b;
> float c;
> } mystruct;
>
> And then I'm using this as a record for a binary file. The problem is
> that the size of the types is different on different
> platforms(win/lin/osx) so if a file was copied on another platform and
> attempted to be read then the first say 16 bytes could be regarded as
> the integer a but it could have been created on system where integer
> was 32 bytes. Is there a portable solution to this? Moreover, I've been
> looking for some resource on designing your own binary format and I
> couldn't find anything apart from short tutorials how to read binary
> files. Are there any good resources?
>
Integers are easy. Just use the AND and OR operators, together with the
bitshifts ( >> <<) to break up an integer into 8-bit chunks, and store it,
big-endian, in a file.

It is necessary to use the big-endian format because otherwise those
little-endians might take over the world, and force us all to store our
bytes at the little end, and we don't wnat that happening.

The float is a bit more tricky. Floating point number have their own
internal format. The good news is that virtually all are 32-bit IEEE format
(sign, exponent, mantissa). You can probably get away with a binary dump,
making sure of the endianness. However to be really portable, you do need to
break the number up into its constitutents, and then rebuild it, using the
ldexp() and frexp() functions.


.



Relevant Pages

  • Re: Intent of C99 6.5#6 ?
    ... In snippet #2, the effective type of y is always 'unsigned int' ... There are a significant number of cases of aliasing that the standard ... union uf {float uff; unsigned long uul;}; ...
    (comp.std.c)
  • Re: short float ???
    ... you mention that "this format is used in the NVIDIA graphic cards, ... floatingpoint" format natively? ... we now have two competing hardware definitions for a "short float". ...
    (comp.std.c)
  • Re: short float ???
    ... you mention that "this format is used in the NVIDIA graphic cards, ... floatingpoint" format natively? ... Although those specific platforms are fairly popular, ... float", or will standard promotion rules apply and computations be ...
    (comp.std.c)
  • Re: Socket & PrintWriter issue-- writing a float to a C client
    ... memcpy(&flt, buffer, 4); ... such as that a float is represented in C memory as 4 ... bytes in IEEE little-endian format -- in which case something like the above ...
    (comp.lang.java.programmer)
  • Re: Accounting changes
    ... 32-bit float format. ... This is the C "float" type on all the architectures we support. ... I could add a typedef clarifying this, but I doubt we'll ever support an architecture where float is a different format. ... these features are provided at no cost by the processor hardware and the C library. ...
    (freebsd-arch)