Endian issues
June 27, 2005

Drunken Blog has been talking about byte-swapping, amongst other things, with regard to the Apple x86 issue.

My comment, having done quite a bit of porting games to the mac from the PC, would be that endian issues accounted for a hell of a lot of my problems, especially the hard-to-track-down bugs where some behaviour quietly changed in some obscure part of the game, without anything actually crashing.

The worst thing tended to be when people cast pointers to (void) or (char) in one place, and then accidentally cast them back to the wrong type somewhere else.

Luckily, incorrect code is actually more likely to work on little endian systems than it is on big endian ones.

This is because, if you have a small value stored in a long, and you take a pointer to the long, then treat it as a pointer to a short (or char), then read the value that it’s pointing to, the value will still be correct on a little endian system, provided that the value actually fits into the short (or char).

On a big endian system, you end up pointing to the other end of the value, which gives totally unexpected results most of the time - if you’re lucky and the value was set as its original type, you’ll get a zero. If you’re unlucky, and the pointer code is doing the setting, whilst some other code is reading the value as the original type, you’ll get uninitialised memory.

Obviously, casting pointers to and from (void) and (char) is a bit of a nasty way to behave generally, but there are legitimate reasons for doing it (well, semi-legitimate, if you’re using old skool C library routines), and it’s easy for mistakes to creep in.

So people with dirty code are going to have some trouble with this. The good news is, over all, getting through the problem will leave their code in a much healthier state.

« UI Scripting with Applescript Autolink Module Update »
Got a comment on this post? Let me know at @samdeane@mastodon.org.uk.