[comp.sources.d] Auto byte swapping

bill@twwells.uucp (T. William Wells) (04/27/89)

Note that followups have been directed to comp.sources.d.

In article <6778@c3pe.UUCP> charles@c3pe.UUCP (Charles Green) writes:
: I'd like to throw in my asynchronous $0.02 worth here.  I've had to write
: programs which run on both architectures, and which use files on their own
: and the "other" machine.  My favorite way to deal with this is to declare a
:
:         union {
:                 char c[2],
:                 short s;
:         } swab;
:
: 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.

Don't do this!

It doesn't work unless shorts are two characters long; there are
plenty of systems where this isn't so.

If you have to read two byte integers from a file, do it a byte at a
time and write an expression to combine the bytes. This is the only
portable way to do it.

---
Bill                            { uunet | novavax } !twwells!bill