Skip to content

Convert to Specified Endianness

AndyGlew edited this page Jun 16, 2020 · 3 revisions

It sometimes (I think often) arises that an application needs to access data written in the opposite format. E.G. for many years little endian PC applications needed to be able to access big endian data formats developed on Apple. Plus the usual network data format.

if the application knows that it is running on a little endian system and is using big endian data, it can do appropriate BSWAPs. and vice versa.

but if the application does not know the endianness of the system it's running on it ends up with a whole slew of

   IF bigendian THEN ... ELSE ...

the if statements are predictable - one does not dynamically change endianness once the program is running - but even always taken branches occupy BTB slots on machines with moderately deep pipelines.

these tend to be a lot of little if statements because the overall logic is often independent of the endianness. Concentrated if you're accessing array data in a single place, but even more scattered if you're accessing structures.

I suppose that you could compile the entire application, or at least a few functions, as big endian or little endian, and reduce the IF statements, but that is often not possible. The linker would need to be aware. not quite so bad, a compiler switch that tries to make the path that corresponds to the endianness of the platform the code is running on of note branches.

I have sometimes wondered if those if statements should be eliminated by having instructions BSWAP_BIGENDIAN that does the swap is running on a little endian system, but which do no swaps if running on a Big Endian system. And vice versa.

Better name (since BSWAP implies that you are always doing something): CONVERT_TO_BIG_ENDIAN, CONVERT_TO_LITTLE_ENDIAN. generically CONVERT_TO_SPECIFIED_ENDIANNESS.

or I suppose CONDITIONAL_BSWAP...


Related:

Byte Address Invariant Endianness versus Word Data Value Invariant Endianness

Clone this wiki locally