Finding out if machine is big/little endian

Started by
4 comments, last by Inmate2993 18 years, 10 months ago
I'm making a simple binary hiscore list, and need to be able to find out whether the machine is big-endian or little-endian. How can I find this out? Thanks.
my siteGenius is 1% inspiration and 99% perspiration
Advertisement
This should work.
bool isBig(){	unsigned short x = 1;	return ((unsigned char*)(&x))[0] == 0;}
Test it.

Declare a 16bit integer. Store the value 1 in it. Declare a byte pointer and point it at the 16bit integer. Read the value. If you get 1, you have little endian, if you get 0, you have big endian.

EDIT: Bah, beaten to the punch.
I'd like to know a way to do this myself, using purely preprocessor macros. Right now I just check the archetecture. If it's x86 or x86-64, it's little endian, if it's PPC it's big endian. If you need more than that, you'll have to look them up (I don't know what other archetectures use, although I'd certainly like to hear if you find out).
Here's a slightly more network-oriented way:

bool host_is_big_endian(){  return htons(1) == 1;}

enum Bool { True, False, FileNotFound };
If you're using SDL, they have a provision for this, I think its #SDL_BYTE_ORDER or something.

Otherwise, use preprocessor macros and a platform dependant header that you can change with each build of the code.

#if HIGH_ENDIAN
x = in[0] + in[1]<<8;
#else
x = in[1] + in[0]<<8;
#endif

And then, HIGH_ENDIAN is defined in the file where DEBUG and stuff would be defined. Stuff you'd change before running a compile, or stuff the ./configure script could set up.
william bubel

This topic is closed to new replies.

Advertisement