[Insight-developers] ByteSwapper seems strange

Kent Williams kent@mail.psychiatry.uiowa.edu
Mon, 3 Mar 2003 10:46:05 -0600


I have noticed some annoying traits of the itk::ByteSwapper template clas=
s,=20
and wonder if there's a rationale at work here that escapes me.

The essence of the class comes down to two sorts of methods:

1. SystemIsBigendian and SystemIsLittleEndian
2. SwapFromSystemToBigEndian and SwapFromSystemToLittleEndian

When you read a file that can be either Little- or Big-Endian you have to=
=20
decide whether or not the current computer is Little- or Big-Endian.  The=
n,=20
if the file has the opposite Endian-ness from the current system, you wan=
t to=20
perform the necessary byte swapping.

But since you don't have SwapFromBigEndianToSystem or=20
SwapFromLittleEndianToSystem, you have to write this wrong-looking code:

if ( ByteSwapper<int>::SystemIsBigEndian() && FileIsLittleEndian )
=09{
=09ByteSwapper<T>SwapFromSystemToLittleEndian(PointerToTypeT);
=09}
else if ( ByteSwapper<int>::SystemIsLittleEndian() && FileIsBigEndian )
=09{
=09ByteSwapper<T>SwapFromSystemToBigEndian(PointerToTypeT);
=09}

which seems a bit absurd.

What I've always done in the past is more like this:

enum Endian { LittleEndian, BigEndian };

Endian FileEndianNess =3D GetFileEndianNess(f);
Endian SystemEndianNess =3D BytesSwapper<int>::GetSystemEndianNess();

if ( FileEndianNess !=3D SystemEndianNess )
=09ByteSwapper<T>Swap(PointerToTypeT);

Now I realize that changing the class completely at this point would requ=
ire=20
some careful editing of multiple files and extensive testing, something n=
o=20
one is presumably contracted to do.  I only noticed that the ByteSwapper=20
seemed obtuse when I discovered that the Analyze FileIO seems to get thin=
gs=20
exactly backwards, and yet seems to do the correct thing.

Has anyone noticed this before? Does someone with more brains for Softwar=
e=20
Engineering than I (and I'm not being sarcastic!) want to suggest a way o=
ut?