[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Interview

Steve Baker wrote:

> A more elegant thing is to store a 'magic number' at the top of the
> file.
> ALL Binary files should start with a 4 byte magic number anyway so that
> you can check that you aren't being fed a file of the wrong kind - and
> also so that the Linux/UNIX 'file' command can be set to recognise your
> file type using /etc/magic.

This sounds interesting; since I don't know zip about unix files, I wonder
if this is actually a standard you're elaborating on, or just something you're
proposing for PFile only ?  I mean, is every Unix file starting with this kind
of magic number ?  And is it a convention to make sure that swapping
is always detectable ? (ie restrict the numbers to shorts where the 4 bytes
make up a strictly increasing sequence or something)

> When you read a file, first read the magic number. If you see 0x1234
> don't
> byte swap - if you see 0x3412, you need to swap.
> The joy of this is that you don't have to byte swap when WRITING files,
> so it halves the amount of work you have to do.  Hence, since each
> machine
> writes files in it's native format, but can read either swapped or not.

Neat !!

Note that there's no need to use a file ofcourse to merely detect swapping;
from the Quake2 source :

void Swap_Init (void)
 byte swaptest[2] = {1,0};

// set the byte swapping variables in a portable manner
 if ( *(short *)swaptest == 1)
  bigendien = false;
  _BigShort = ShortSwap;
  _LittleShort = ShortNoSwap;
  _BigLong = LongSwap;
  _LittleLong = LongNoSwap;
  _BigFloat = FloatSwap;
  _LittleFloat = FloatNoSwap;
  bigendien = true;
  _BigShort = ShortNoSwap;
  _LittleShort = ShortSwap;
  _BigLong = LongNoSwap;
  _LittleLong = LongSwap;
  _BigFloat = FloatNoSwap;
  _LittleFloat = FloatSwap;

and those functions then go like this :

float FloatSwap (float f)
  float f;
  byte b[4];
 } dat1, dat2;

 dat1.f = f;
 dat2.b[0] = dat1.b[3];
 dat2.b[1] = dat1.b[2];
 dat2.b[2] = dat1.b[1];
 dat2.b[3] = dat1.b[0];
 return dat2.f;

float FloatNoSwap (float f)
 return f;

So by initializing the short array with the magic number read in
and then comparing it to what it should be, all these functions can
be init'ed and then just applied when the struct is read...
Well you all knew that ofcourse, just thought I'd post this code,
if you want I can dump the entire listing here if you don't feel like
installing the sources just for that :)


-=<Short Controlled Bursts>=-