Auto byte swapping (was Re: fixed unzip)

Jordan Brown jbrown at jato.Jpl.Nasa.Gov
Fri Apr 28 13:13:09 AEST 1989


In article <6778 at c3pe.UUCP> charles at c3pe.UUCP (Charles Green) writes:
>and stuff, say, a 0x0102 into swab.s and see what winds up in c[0] to find
>out which type of machine you're on.  If you're dealing with an existing
>file, you read the magic into swab.s and, depending on what shows up in
>c[0], you know whether it's "your" format or not, and can swap bytes as
>required in your program to compensate.

There's an even better way.  Keep a tag in your file (or net packet) which
indicates your byte order.  Whenever you create a file (or packet), stuff
0x0102 into this "order" word.  Whever you read one of these files, look
at the "order" word.  If it's 0x0102, you don't need to swap anything.
If it's 0x0201, then swap everything.  This works on either order; you
don't need to know what you are or what the originator was.  It also saves
swapping completely when the writer and reader are the same machine type,
which is presumably a common case.

If you want compatibility with the Ritchie PDP-11 compiler, which stores
longs as middle-high, high, low, middle-low (rather than Vax low, middle-low,
middle-high, high), then use a 4-byte tag.  The exact algorithm is left
as an exercise for the reader.



More information about the Alt.sources mailing list