Re: Robust detection of endianness at compile time.

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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.


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux