Calculating Endian type at runtime (and adapting to it)
Well I've researched some endian calculating techniques and can't find a way to achieve what I want. I basically want to have a certain union type name be associated with the union that corresponds with the correct endian.
This is what I have so far and I know it doesnt work, I'm not very good at preprocessor directives because I really dont ever use them, but I've tried everything so I just left it in the code. Here is the code, it calculates the correct endian (I think) but just doesn't define the right type.
Code:
#include <iostream>
using namespace std;
/////////////////////////////////////////////////
typedef unsigned int CHAR32;
//-----------------------------------------------
// Breaks up 32 bits into blocks of 8 bits
// BITBLOCKSB for Big-Endian
// BITBLOCKSL for Little-Endian
//-----------------------------------------------
struct BITBLOCKSB {
unsigned char one;
unsigned char two;
unsigned char three;
unsigned char four;
};
struct BITBLOCKSL {
unsigned char four;
unsigned char three;
unsigned char two;
unsigned char one;
};
//-----------------------------------------------
// Allows access to the bit blocks of a value
// BITUNIONB for Big-Endian
// BITUNIONL for Little-Endian
//-----------------------------------------------
typedef union {
CHAR32 value;
BITBLOCKSB bits;
} BITUNIONB;
typedef union {
CHAR32 value;
BITBLOCKSL bits;
} BITUNIONL;
//-----------------------------------------------
// Current PC endian type
//-----------------------------------------------
bool ENDIAN() {
short int bit = 1;
char* byte = (char*) &bit;
return (byte[0] ? true : false);
}
//-----------------------------------------------
const bool BIGENDIAN = ENDIAN();
//-----------------------------------------------
#if (BIGENDIAN)
#define BITUNION BITUNIONB
#else
#define BITUNION BITUNIONL
#endif
/////////////////////////////////////////////////
int main() {
BITUNION bitUnion;
bitUnion.value = 254;
cout << (int)bitUnion.bits.one << " " << (int)bitUnion.bits.two << " "
<< (int)bitUnion.bits.three << " " << (int)bitUnion.bits.four;
cout << endl << "Big Endian? " << (BIGENDIAN ? " Yes" : " No") << endl;
cin.get();
return 0;
}