Jump to content

  • Log In with Google      Sign In   
  • Create Account

We're offering banner ads on our site from just $5!

1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


Don't forget to read Tuesday's email newsletter for your chance to win a free copy of Construct 2!


Best way to check endianness at run-time?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
18 replies to this topic

#1 TimA   Members   -  Reputation: 139

Like
0Likes
Like

Posted 06 March 2013 - 07:42 PM

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



Sponsor:

#2 ultramailman   Prime Members   -  Reputation: 1582

Like
1Likes
Like

Posted 06 March 2013 - 08:02 PM

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.

Edited by ultramailman, 06 March 2013 - 09:01 PM.


#3 Bregma   Crossbones+   -  Reputation: 5248

Like
6Likes
Like

Posted 06 March 2013 - 08:08 PM

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

#4 TimA   Members   -  Reputation: 139

Like
0Likes
Like

Posted 06 March 2013 - 08:34 PM

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



#5 ultramailman   Prime Members   -  Reputation: 1582

Like
1Likes
Like

Posted 06 March 2013 - 08:49 PM

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.

#6 frob   Moderators   -  Reputation: 22242

Like
8Likes
Like

Posted 06 March 2013 - 08:58 PM

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.

Check out my book, Game Development with Unity, aimed at beginners who want to build fun games fast.

Also check out my personal website at bryanwagstaff.com, where I write about assorted stuff.


#7 0r0d   Members   -  Reputation: 819

Like
1Likes
Like

Posted 06 March 2013 - 10:59 PM

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.



#8 Cornstalks   Crossbones+   -  Reputation: 6991

Like
3Likes
Like

Posted 06 March 2013 - 11:32 PM

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;
    }
}

Edited by Cornstalks, 06 March 2013 - 11:34 PM.

[ 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 ]

#9 TimA   Members   -  Reputation: 139

Like
0Likes
Like

Posted 06 March 2013 - 11:50 PM

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

Edited by TimA, 06 March 2013 - 11:54 PM.


#10 Hodgman   Moderators   -  Reputation: 31092

Like
2Likes
Like

Posted 07 March 2013 - 12:16 AM

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

#11 Khatharr   Crossbones+   -  Reputation: 3031

Like
0Likes
Like

Posted 07 March 2013 - 12:31 AM

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.

#12 larspensjo   Members   -  Reputation: 1557

Like
4Likes
Like

Posted 07 March 2013 - 02:58 AM

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.

 

Please read The byte order fallacy, which I think summarizes it all perfectly!


Current project: Ephenation.
Sharing OpenGL experiences: http://ephenationopengl.blogspot.com/

#13 Khatharr   Crossbones+   -  Reputation: 3031

Like
0Likes
Like

Posted 07 March 2013 - 09:10 AM

Nice link. That sums it up quite definitively.


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.

#14 Kylotan   Moderators   -  Reputation: 3338

Like
2Likes
Like

Posted 07 March 2013 - 09:20 AM

Or just use htonl/ntohl etc. to write the values in a standardised order. That code should work on all machines.



#15 rip-off   Moderators   -  Reputation: 8518

Like
5Likes
Like

Posted 07 March 2013 - 03:37 PM

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.



#16 TimA   Members   -  Reputation: 139

Like
0Likes
Like

Posted 10 March 2013 - 12:49 PM

Thanks for all the info, you've all gave me different aspects to consider when I decide to switch my map format over to binary.  Think I'm gonna save that task for after mid-terms though.



#17 osmanb   Crossbones+   -  Reputation: 1614

Like
0Likes
Like

Posted 10 March 2013 - 01:56 PM

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.

 

Please read The byte order fallacy, which I think summarizes it all perfectly!

 

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:

 

#if PLATFORM_WIN64
#define LITTLE_ENDIAN
#elif PLATFORM_PS3
#define BIG_ENDIAN
#else
#error Need to specify endianness for new platform!
#endif


#18 Cornstalks   Crossbones+   -  Reputation: 6991

Like
1Likes
Like

Posted 10 March 2013 - 02:44 PM

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.


[ 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 ]

#19 wintertime   Members   -  Reputation: 1799

Like
0Likes
Like

Posted 11 March 2013 - 01:56 PM

Both of your problems is not only a problem with the cleaner always shifting code but also with the #ifdef BIGENDIAN twiddlings and there its maybe not even tested.

1. That can easily be fixed in both with explicit casts to int32_t before shifting.

2. With that you would probably just do a pointer cast. Floats and doubles are ultimately just some data bytes you read in too.






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS