Best way to check endianness at run-time?

Started by
17 comments, last by wintertime 11 years, 1 month ago

Okay first off I found this:


bool endianness() {
     int i = 1;
     char *ptr;
     ptr  = (char*) &i;
     return (*ptr);
}

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?

I'm trying to accomplish something like this (pseudo-code):


enum ENDIANNESS {UNKNOWN, LITTLE_ENDIAN, BIG_ENDIAN};

ENDIANNESS getEndian()
{
     ENDIANESS e = UNKNOWN;

     get a 2 byte numeric data type;

     set bytes value equal to 1;

     get first byte

     if ( first byte == 0)
     {
          e = BIG_ENDIAN
     }
    else  if ( first byte == 1)
     {
          e = LITTLE_ENDIAN
     }

     return e;

}

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).

Any help is greatly appreciated :)

Advertisement

char isn't guranteed to be one byte

I remember from somewhere that char is always one byte. Then short <= int <= long <= long long.

If you are worrying about this, why not use long or long long instead of int? They might be bigger than int.
int endianess(void)
{
        union{
                long long l;
                char c[sizeof(long long)];
        } n = {1};
        return n.c[0];
}
Also check out stdint.h, if the compiler you use supports it.

Any reason you want to do this at runtime? Will the endianness ever change on the machine your software runs on?

Stephen M. Webb
Professional Free Software Developer

@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.
Okay... Why?

The problem requires absolutely zero runtime code.

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:


#ifdef platform
#define LITTLEENDIAN
#endif
#ifdef otherplatform
#define BIGENDIAN
#endif.

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.

Okay... Why?

The problem requires absolutely zero runtime code.

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:


#ifdef platform
#define LITTLEENDIAN
#endif
#ifdef otherplatform
#define BIGENDIAN
#endif.

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)


#ifdef WIN32
	typedef unsigned int	u32;
	typedef unsigned char	u8;
#else
	// add defines here for other platforms
#endif

bool IsLittleEndian()
{
	u32 i = 1;
	u8 *ptr  = (u8*) &i;
	return (*ptr);
}

If you're supporting multiple platforms, these will be things you already have, so that should require no new code per platform.

Lastly, you shoudnt name functions like "bool endianness(void)" because it tells you nothing about what it does or returns.

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

sizeof(char) is required to always be 1 (or in other words, a char is always 1 "byte," but this "byte" doesn't have to be 8 bits (it will be at least 8 bits, but could be more).

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

sizeof(char) <= sizeof(int). Additionally, int is required to be at least 16 bits. It's possible char and int are both 16 (or greater) data types.

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;
    }
}
[size=2][ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]
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

Any reason you want to do this at runtime? Will the endianness ever change on the machine your software runs on?

Following on from this, are you actually writing software that will be portable to an 8-bit CPU?

The easiest way is to ask the user who is compiling your code to define either IS_BIG_ENDIAN or IS_LITTLE_ENDIAN ;P
There's other options here: http://stackoverflow.com/questions/2100331/c-macro-definition-to-determine-big-endian-or-little-endian-machine

On any POSIX system, char will be 8 bits (CHAR_BIT always == 8).

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'.

This topic is closed to new replies.

Advertisement