I like the way this is done, it's clever, quick and gets the job done. Except it only really works if the size of an int is at-least twice the size of a char. As I understand it the data types don't have a set size and that each 'larger' data type only has to be greater than or equal to the 'next smallest' data type. Considering endianness is architecture specific, and the size of data types would differ on different architectures, this seems to be an unsafe assumption.

There's a lot of garbage information out there on endianness but from what I've gathered (and please correct me if I'm wrong):

char isn't guranteed to be one byte, it seems it's usually the size of whatever the processor processes things in, which is sometimes 16-bit (2 byte) increments

integer can be 1 byte on some architectures, which would break this code

I also have one question, is endianness byte ordering always based on 8-bit bytes or would it be ordered in sections of 16-bits on architectures with 16-bit chars?

Just not sure the best way to handle this, especially since I'm unclear on whether the byte order is based on 8-bits always (seems unlikely) or whatever the size of a char is on the system executing the code (seems more likely).

@ultramailman: Because so far I've read about systems with 16-bit, 24-bit, and 32-bit chars, some having a int the same size as char, and some having the same size long as int (though I don't really know the point of that) I agree that it should work with most systems if i were to evaluate something the size of char out of something the size of long long, it just seems bad practice to write something I know won't work in every situation.

@Bregma: No, I suppose this could happen at compile time, not sure how to go about that either though. Seems like it'd be easier to do at run-time.

Even if a char is 16, 24 or 32 bits, it still holds that char <= short <= int <= long <= long long. So I think using long long is the better than int. On a system where long long is one byte (same as char), wouldn't the endianess be considered as both big and small at the same time (Schrodinger's endian O_o)? So it wouldn't matter if that is the case.

First, why do you need to check endianness? Are you honestly developing on various machines? Perhaps you are sharing c++ code between an arm processor and an x86 processor? That isn't very common, and if you are doing it then you will already have a bunch of platform-specific #ifdef statements scattered through your code. Now you'll just have two more:

Your endianness does not change mid execution. Either you are compiled for one platform or you are compiled for another platform.

And if you are developing something that spans platforms you are going to need an awful lot of code far beyond that. You'll need to build every resource loader, every file manager, every asset, and any fancy bit-tricks, and have variations for each platform.

Detecting endianness isn't really a thing. There really isn't a point to it.

First, why do you need to check endianness? Are you honestly developing on various machines? Perhaps you are sharing c++ code between an arm processor and an x86 processor? That isn't very common, and if you are doing it then you will already have a bunch of platform-specific #ifdef statements scattered through your code. Now you'll just have two more:

Your endianness does not change mid execution. Either you are compiled for one platform or you are compiled for another platform.

And if you are developing something that spans platforms you are going to need an awful lot of code far beyond that. You'll need to build every resource loader, every file manager, every asset, and any fancy bit-tricks, and have variations for each platform.

Detecting endianness isn't really a thing. There really isn't a point to it.

You dont NEED any runtime code, but the runtime solution does have the benefit that it requires ZERO additional defines to add in order to support a new platform. Sure, this will be minimal compared to the other stuff you'll probably need to define per platform... but it's still something. If the OP wants code that is GUARANTEED to work when new platforms are added, with no added code, then that's the way to go. If performance is an issue, then compile time is best.

As far as what to do to make sure the runtime function always works... you probably want to use constant size data types that you define (i.e. u32 instead of int, u8 instead of char)

I also have one question, is endianness byte ordering always based on 8-bit bytes or would it be ordered in sections of 16-bits on architectures with 16-bit chars?

Endianness is about byte ordering, but here "byte" doesn't have to mean 8 bit groups. If you're on a system with 16 bit bytes, then a two byte word (32 bits) would still have endianness (because it's made up of two (16 bit) bytes, and the order of those bytes in memory determines endianness). A single byte (no matter how many bits are in it) does not have any endianness. Endianness has to do with the ordering of bytes, not the ordering of bits.

I would suggest doing this check at compile time. If you still want to do some kind of runtime switching (for whatever insane reason), you can hide the compile time code inside of a function and still call the function at run time. There's no reason to be checking at runtime by messing with pointers.

Beware, however, that if you do use compile time checking, that you do it properly. If you are cross compiling your program and you relied on some bad macros, it's possible you may detect the endianness of the compiling platform instead of the target platform.

For what it's worth, there may not be any endianness to a system. For example, if sizeof(char) == sizeof(short) == sizeof(int) == sizeof(long) == sizeof(long long), then the system doesn't really have any endianness since everything is one byte. Thus, to be uber pedantic, you would check if the system is big endian, little endian, or "no endian."

Anyway, like I said, I would check using compiler flags/preprocessing/macros (i.e. check at compile time). If you really wanted to check at runtime, you can do:

// This is, of course, assuming that a system is either big, little, or no endian. It's
// technically possible for a system to be middle endian: http://en.wikipedia.org/wiki/Endianness#Middle-endian
// Also note that its technically possible for integer and floating point data types to
// have different endianness: http://en.wikipedia.org/wiki/Endianness#Floating-point_and_endianness
// To be honest, you just have to draw the line somewhere and say "We support A, B, and C."
// It's really not worth your time trying to support everything under the sun. Just
// come up with a sane set of basic requirements that you think are realistic for your
// target market.
enum Endianness
{
BIG,
LITTLE,
NONE
};
Endianness checkEndianness()
{
// Note: Before C11, unsigned char was the only data type that was guaranteed to not have any padding bits.
// Since C11, that has since been changed so that both signed char and unsigned char have no padding bits.
// I'm not sure if C++11 says whether or not signed char may have padding bits, but unsigned char certainly
// does not.
// I would personally actually use macros to detect endianness at compile time, and just make this function
// return the endianness as a compile time flag.
unsigned long long a = 1;
if (sizeof(a) == sizeof(unsigned char))
{
return NONE;
}
else if (*(unsigned char*)&a == 1)
{
return LITTLE;
}
else
{
return BIG;
}
}

Yeah the bool endianness was something I found online - ENDIAN getEndian() is what I was planning on calling it, returning an enumerated type defined right above it.

Am I developing on multiple machines? No - I would like to develop with more than just my machines architecture in mind though. The library I'm more or less extending does all the low-level stuff inside. Not a whole lot of binary manipulation going on at my end. Except I am designing a binary file format to store map data and if someone creates a map on a big-endian system, and someone else loads it on a little-endian system it's either going to crash, or load something crazy.

Awesome point about the constant sized data types - I will probably go that route.

I have very little experience in cross-platform support, so if you wanna throw some links at me with some essential "you should know this so you don't f*ck everything up" type of info in it, I'd be appreciative, but other than loading binary file formats and data types being different sizes on different platforms I don't really see what platform specific code I'd need.

I'll do more research later, right now I need to get to bed though...2 back to back math tests in 6 hours...yay *sarcasm*

Edit: Cornstalks - just saw your post - awesomely informative and cleared up a lot of the gray area

On any C compiler, memory is addressed in 'chars'.If int is the same size of a char, then endianess doesn't apply, because endianess is about at which end you start from when breaking something down into bytes/'chars'.

The same code can generally compile and run without problems on systems with diverse endianness (provided it's compiled for the appropriate targets). It's usually only something that you need to worry about when dealing with data between machines, and in that case you're better off using a compile-time macro that ensures that data is in the correct format or else is converted.

In order to encounter endianness problems in the code itself you'd have to get up to the same flavor of hackery that's going on in your test function there, which probably isn't good, and at least should be a rare occurrence.

Long story short, if it's not causing errors then don't mess with it.

void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

As also have been mentioned above, there is a risk that you are falling into a common trap here. Data (or protocols) can be little endian or big endian, but you should never worry about what the current machine/system has.

I would be wary of pretending to support platforms unless you build and test on them. I don't mean to say that you should write unportable code, but don't think that patchwork of untested preprocessor branches is writing portable code.

As also have been mentioned above, there is a risk that you are falling into a common trap here. Data (or protocols) can be little endian or big endian, but you should never worry about what the current machine/system has.

I was also going to link to that article, but you beat me to it. For the use-case being described here, i think it's pretty accurate. However, as much respect as I have for all the Bell Labs folks, there is more to the story. In the ideal world where computers are infinitely fast, reading and writing every multi-byte value one byte at a time may be great. For those of us making games that need to load 100s of MBs with minimal delay -- not so much. I'd love to ignore the endianness of each platform we support, and serialize all data in one consistent format. But then we'd be iterating over all of that data at load time, instead of loading up a block of memory and doing pointer fixup.

All of that said, our solution is exactly as frob has indicated: We just #define it at compile time. We need to declare lots of things about each platform we support, we just add endianness to the list. It's really not hard. The #if/#elif chain for each of those decisions always looks like:

I have some issues with that "The byte order fallacy" post, and since I can't post on his blog, I'm going to leave my comments here:

1. He claims his code "computes a 32-bit integer value regardless of the local size of integers" which is not quite correct. If an int is not 32-bits (particularly, if it's less than 25 bits), his code is invoking undefined behavior (shifting an N-bit number by N or more bits is undefined behavior).

2. He only talks about the simplest case: reading/writing ints. Other data types, like float or double, can't be magically written or read like he shows.

I can't think of other nitpicks. In general, I think he makes a good point, but I think he's being overly critical of the endian-specific method while not being critical enough of his own version. If he's going to be critical, he should be critical to both.