This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: Robust detection of endianness at compile time.
- From: "Lee Rhodes" <lee at rhoba dot com>
- To: <gcc-help at gcc dot gnu dot org>, <nmm1 at cam dot ac dot uk>, "'Brian Dessent'" <brian at dessent dot net>, "'Andrew Haley'" <aph-gcc at littlepinkcloud dot COM>, <iant at google dot com>
- Date: Mon, 30 Jul 2007 15:03:53 -0700
- Subject: Re: Robust detection of endianness at compile time.
Folks,
Thinking about detection of endianness at *run-time* got me
thinking...would this work, at least on machines with 32 bit IEEE 754 float,
32 bit unsigned long and 8 bit char?
#include <iostream>
union endian {
float f;
unsigned long i;
unsigned char c[4];
};
inline int testEndian();
int testEndian() {
register endian e;
register int out = 0;
e.i = 1U << 24;
if (e.c[3] == 1) out |= 1; //Little Endian Integers
e.i = 3U << 30;
if (e.f < 0) out |= 2; //Little Endian Float
return out;
}
using namespace std;
int main() {
int t = testEndian();
if ((t & 1) == 1) cout << "Little Endian Integer" << endl;
else cout << "Big Endian Integer" << endl;
if ((t & 2) == 2) cout << "Little Endian Float" << endl;
else cout << "Big Endian Float" << endl;
}
This may not require a memory access if the compiler actually uses registers
and if the machine instruction set utilized small immediate values within
the instruction itself. I don't have a big-endian machine, but if one of
you has one could you try it?
Forget the middle-endian can-of-worms!
Lee.