• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
TimA

Best way to check endianness at run-time?

18 posts in this topic

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

0

Share this post


Link to post
Share on other sites

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
1

Share this post


Link to post
Share on other sites

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

0

Share this post


Link to post
Share on other sites
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.
1

Share this post


Link to post
Share on other sites

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.

1

Share this post


Link to post
Share on other sites
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
0

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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

2

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

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.

1

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0