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: Andrew Haley <aph-gcc at littlepinkcloud dot COM>
- To: "Lee Rhodes" <lee at rhoba dot com>
- Cc: <gcc-help at gcc dot gnu dot org>, <nmm1 at cam dot ac dot uk>, "'Brian Dessent'" <brian at dessent dot net>, <iant at google dot com>
- Date: Tue, 31 Jul 2007 13:56:07 +0100
- Subject: Re: Robust detection of endianness at compile time.
- References: <002201c7d2f5$85f64c00$0701a8c0@lee8075b>
Lee Rhodes writes:
> 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?
It would work on gcc, because gcc allows members of a union to be
written as one type and read as a different incompatible type. Other
C compilers allow this too. However, it's is not guaranteed by the
language standards, so it doesn't much help you with truly portable
code.
Andrew.