# Finding out if machine is big/little endian

This topic is 4816 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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.

##### Share on other sites
This should work.
bool isBig(){	unsigned short x = 1;	return ((unsigned char*)(&x))[0] == 0;}

##### Share on other sites
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.

##### Share on other sites
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).

##### Share on other sites
Here's a slightly more network-oriented way:

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

##### Share on other sites
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.

1. 1
2. 2
frob
16
3. 3
4. 4
5. 5
Rutin
10

• 18
• 13
• 14
• 76
• 22
• ### Forum Statistics

• Total Topics
632149
• Total Posts
3004365

×