29

I'm currently trying to create a C source code which properly handles I/O whatever the endianness of the target system.

I've selected "little endian" as my I/O convention, which means that, for big endian CPU, I need to convert data while writing or reading.

Conversion is not the issue. The problem I face is to detect endianness, preferably at compile time (since CPU do not change endianness in the middle of execution...).

Up to now, I've been using this :

#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
...
#else
...
#endif

It's documented as a GCC pre-defined macro, and Visual seems to understand it too.

However, I've received report that the check fails for some big_endian systems (PowerPC).

So, I'm looking for a foolproof solution, which ensures that endianess is correctly detected, whatever the compiler and the target system. well, most of them at least...

[Edit] : Most of the solutions proposed rely on "run-time tests". These tests may sometimes be properly evaluated by compilers during compilation, and therefore cost no real runtime performance.

However, branching with some kind of << if (0) { ... } else { ... } >> is not enough. In the current code implementation, variable and functions declaration depend on big_endian detection. These cannot be changed with an if statement.

Well, obviously, there is fall back plan, which is to rewrite the code...

I would prefer to avoid that, but, well, it looks like a diminishing hope...

[Edit 2] : I have tested "run-time tests", by deeply modifying the code. Although they do their job correctly, these tests also impact performance.

I was expecting that, since the tests have predictable output, the compiler could eliminate bad branches. But unfortunately, it doesn't work all the time. MSVC is good compiler, and is successful in eliminating bad branches, but GCC has mixed results, depending on versions, kind of tests, and with greater impact on 64 bits than on 32 bits.

It's strange. And it also means that the run-time tests cannot be ensured to be dealt with by the compiler.

Edit 3 : These days, I'm using a compile-time constant union, expecting the compiler to solve it to a clear yes/no signal. And it works pretty well : https://godbolt.org/g/DAafKo

Cyan
  • 13,248
  • 8
  • 43
  • 78
  • 1
    @BoPersson - this is not a compile time detection – MByD Jan 23 '12 at 21:40
  • Some CPUs actually *can* have different endianness for different executables. http://en.wikipedia.org/wiki/Endianness#Bi-endian_hardware – Bo Persson Jan 23 '12 at 21:47
  • @bo : indeed, i've checked this question too, but unfortunately it's a run-time detection. It advises to depend on the result of a function. This might be okay for some other use, but I need a compile (preprocessor) detection. – Cyan Jan 23 '12 at 21:47
  • 1
    @Cyan , bar the ones you've mentioned, there isn't one. So either compile a small program that detects the endianess, and feed the result into your build system so it defines a preprocessor macro, or write the code so it is independent of the host endianess. – nos Jan 23 '12 at 22:02
  • Run-time detection is a great interview question :) – Danra Jan 23 '12 at 22:10
  • 1
    Run time is your best bet, but compile time is included in the below answers: 1. http://stackoverflow.com/a/1001373/1094175 2. http://stackoverflow.com/a/2100385/1094175 – Brett McLain Jan 23 '12 at 21:43
  • 3
    The reason your preprocessor-based test can fail (false positive) is that undefined symbols get replaced with `0` in `#if` directives. – R.. GitHub STOP HELPING ICE Jan 24 '12 at 01:23
  • @R. : +1, yes, i guess this is why it seems to works for Visual. – Cyan Jan 24 '12 at 10:58

17 Answers17

23

As stated earlier, the only "real" way to detect Big Endian is to use runtime tests.

However, sometimes, a macro might be preferred.

Unfortunately, I've not found a single "test" to detect this situation, rather a collection of them.

For example, GCC recommends : __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ . However, this only works with latest versions, and earlier versions (and other compilers) will give this test a false value "true", since NULL == NULL. So you need the more complete version : defined(__BYTE_ORDER__)&&(__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)

OK, now this works for newest GCC, but what about other compilers ?

You may try __BIG_ENDIAN__ or __BIG_ENDIAN or _BIG_ENDIAN which are often defined on big endian compilers.

This will improve detection. But if you specifically target PowerPC platforms, you can add a few more tests to improve even more detection. Try _ARCH_PPC or __PPC__ or __PPC or PPC or __powerpc__ or __powerpc or even powerpc. Bind all these defines together, and you have a pretty fair chance to detect big endian systems, and powerpc in particular, whatever the compiler and its version.

So, to summarize, there is no such thing as a "standard pre-defined macros" which guarantees to detect big-endian CPU on all platforms and compilers, but there are many such pre-defined macros which, collectively, give a high probability of correctly detecting big endian under most circumstances.

Cyan
  • 13,248
  • 8
  • 43
  • 78
  • 4
    Writing for other people who find this answer useful. gcc supports `__BYTE_ORDER__` from about 4.6 and clang from 3.2 – Andrei Jul 10 '19 at 05:14
  • You can write `static_assert(__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__);` which works on GCC, and will otherwise fail on compilers that don't define these. – Brent May 26 '22 at 19:56
17

At compile time in C you can't do much more than trusting preprocessor #defines, and there are no standard solutions because the C standard isn't concerned with endianness.

Still, you could add an assertion that is done at runtime at the start of the program to make sure that the assumption done when compiling was true:

inline int IsBigEndian()
{
    int i=1;
    return ! *((char *)&i);
}

/* ... */

#ifdef COMPILED_FOR_BIG_ENDIAN
assert(IsBigEndian());
#elif COMPILED_FOR_LITTLE_ENDIAN
assert(!IsBigEndian());
#else
#error "No endianness macro defined"
#endif

(where COMPILED_FOR_BIG_ENDIAN and COMPILED_FOR_LITTLE_ENDIAN are macros #defined previously according to your preprocessor endianness checks)

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
  • 1
    The value of a union member other than the last one stored into is an unspecified behavior in C. – ouah Jan 23 '12 at 21:53
  • 1
    @ouah: the C standard knows nothing about endianness, so we are already going out of the standard domain and working on implementation-specific behavior (and I don't think you'll ever find a compiler implementing `union`s differently or an optimizer messing with them). Although, I agree that the other "classic method" (cast of the pointer to `char *`) does not exhibit UB problems due to the exceptions to the aliasing rules. – Matteo Italia Jan 23 '12 at 22:00
  • @ouah: also, §6.7.2.1 doesn't mention UB, it just says that "The value of at most one of the members can be stored in a union object at any time"; also, I dare to say that §6.7.2.1 ¶14 implicitly allows the use of `union`s as a replacement for that cast, since "A pointer to a union object, suitably converted, points to each of its members [...] and vice versa.". So, `&u.i = &u = &u.c` (with the appropriate casts), thus `u.c[0] = (*(&u.c))[0]=*((char *)&u.i)`, which is as legal as the "other method". – Matteo Italia Jan 23 '12 at 22:13
  • In C99, Annex J (non-normative) "J.1 Unspecified behavior. The following are unspecified: The value of a union member other than the last one stored into (6.2.6.1)." and 6.2.6.1p7 says "When a value is stored in a member of an object of union type, the bytes of the object representation that do not correspond to that member but do correspond to other members take unspecified values." – ouah Jan 23 '12 at 22:20
  • @ouah: the first one is solved by working on §6.7.2.1 ¶14 as I already wrote before (it's still unspecified behavior, but exactly as it is the cast - and hey, that code is there to understand exactly how the compiler implements that "unspecified behavior"). Your second quotation is irrelevant, since the two members in my union are of the same size, so both members "completely fill" the `union` (and this would still hold even if I declared a single `char`, because the biggest member is stored first). – Matteo Italia Jan 23 '12 at 22:28
  • yes the second quote is actually irrelevant. +1 for the addition of the pedantic version I just see now;) – ouah Jan 23 '12 at 22:55
  • That's a good idea. Unfortunately, the number of functions to duplicate in this case is a bit too high (8), and will hamper future code maintenance. The basic idea was to embed the small differences due to endianess into macro (or inlined functions), keeping the code leans and common to all platforms. – Cyan Jan 28 '12 at 10:39
  • Better not call your macros `BIG_ENDIAN` and `LITTLE_ENDIAN` -- `` on Linux/*BSD defines macros by such names, and they will therefore both be always defined if you happen to `include `. – Lauri Nurmi May 08 '18 at 11:52
  • @LauriNurmi: woa, well spotted; I'll change them to something else. – Matteo Italia May 08 '18 at 12:42
17

Instead of looking for a compile-time check, why not just use big-endian order (which is considered the "network order" by many) and use the htons/htonl/ntohs/ntohl functions provided by most UNIX-systems and Windows. They're already defined to do the job you're trying to do. Why reinvent the wheel?

Chris Lutz
  • 73,191
  • 16
  • 130
  • 183
  • Good point. Unfortunately, i cannot change this convention now, since the code has been in use for quite some time now, and it needs to remain compatible with existing user data. – Cyan Jan 23 '12 at 22:28
  • @Cyan - Ah. In that case you're going to have to run a build-time check with something like autoconf to define the macro for you, or settle for a runtime solution. – Chris Lutz Jan 23 '12 at 22:32
  • This only works if don't have any 64-bit data types. At least on linux, htonl returns a `uint32_t`, not an `unsigned long`, so even on 64-bit platforms, it should operate on 32-bit values. That's usually the desired behavior for the function to work correctly with existing networking code. – Brian McFarland Jan 23 '12 at 22:44
  • @BrianMcFarland - Yeah, when I looked through the manpages I thought, "I remember this function family being a lot more useful the last time I encountered them." I suppose people will usually have to implement their own platform-dependent wrappers. I wonder if any compilers optimize various runtime-endian-check idioms into compile-time constants to reduce code execution paths? – Chris Lutz Jan 24 '12 at 00:07
11

Try something like:

if(*(char *)(int[]){1}) {
    /* little endian code */
} else {
    /* big endian code */
}

and see if your compiler resolves it at compile-time. If not, you might have better luck doing the same with a union. Actually I like defining macros using unions that evaluate to 0,1 or 1,0 (respectively) so that I can just do things like accessing buf[HI] and buf[LO].

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
  • 1
    This particular example doesn't compile. Maybe it is meant to be used on C++ ? It seems it doesn't respect C limitations on var initialisation. – Cyan Jan 27 '12 at 18:29
  • 4
    It's written in the current C language, not C89. You're probably using a backwards compiler like MSVC, in which case you'll need to adapt it a bit.. – R.. GitHub STOP HELPING ICE Jan 27 '12 at 18:33
  • Indeed, i'm testing the source code with both MSVC and GCC. The code should work with both. – Cyan Jan 27 '12 at 19:29
9

Notwithstanding compiler-defined macros, I don't think there's a compile-time way to detect this, since determining the endianness of an architecture involves analyzing the manner in which it stores data in memory.

Here's a function which does just that:

bool IsLittleEndian () {

    int i=1;

    return (int)*((unsigned char *)&i)==1;

}
6

As others have pointed out, there isn't a portable way to check for endianness at compile-time. However, one option would be to use the autoconf tool as part of your build script to detect whether the system is big-endian or little-endian, then to use the AC_C_BIGENDIAN macro, which holds this information. In a sense, this builds a program that detects at runtime whether the system is big-endian or little-endian, then has that program output information that can then be used statically by the main source code.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • [I've heard](https://sourceforge.net/p/predef/wiki/Endianness/) this method may cause problems in a cross-compile environment, where the endianness of the target system is different from the endianness of the build system. – Craig McQueen Dec 31 '12 at 12:26
  • You should provide an example of using Autotools' `AC_C_BIGENDIAN`. This was the first Stack Overflow reference for a search of "Autoconf AC_C_BIGENDIAN", but it lacks the example I was hoping for. – jww Nov 06 '17 at 21:14
4

This comes from p. 45 of Pointers in C:

#include <stdio.h>
#define BIG_ENDIAN 0
#define LITTLE_ENDIAN 1

int endian()
{
   short int word = 0x0001;
   char *byte = (char *) &word;
   return (byte[0] ? LITTLE_ENDIAN : BIG_ENDIAN);
}

int main(int argc, char* argv[])
{
   int value;
   value = endian();
   if (value == 1)
      printf("The machine is Little Endian\n");
   else
      printf("The machine is Big Endian\n");
   return 0;
}
Geremia
  • 4,745
  • 37
  • 43
4

Socket's ntohl function can be used for this purpose. Source

// Soner
#include <stdio.h>
#include <arpa/inet.h>


int main() {
    if (ntohl(0x12345678) == 0x12345678) {
        printf("big-endian\n");
    } else if (ntohl(0x12345678) == 0x78563412) {
        printf("little-endian\n");
    } else {
        printf("(stupid)-middle-endian\n");
    }
    return 0;
}
4

My GCC version is 9.3.0, it's configured to support powerpc64 platform, and I've tested it and verified that it supports the following macros logic:

#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
......
#endif
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
.....
#endif
Clock ZHONG
  • 875
  • 9
  • 23
  • 1
    I remember using this method initially. The problem is : it tends to work on system I test on, but it may not work for some other systems. Depending on your portability objectives, it might be a liability or not. In my case, since I don't control which systems my software run, I have to target maximum portability. It made this macro check undesirable. I instead use a runtime test, which is effectively transformed into a compile-time constant by the compiler. – Cyan Jun 02 '21 at 16:12
  • 1
    @ClockZHONG note that the bold here is two underscores (ie `__`) so read __LITTLE_ENDIAN__ as `__LITTLE_ENDIAN__` – Czipperz Sep 03 '21 at 23:38
  • @Cyan I remember in old versions PPC toolchain, they use LITTLE_ENDIAN & BIG_ENDIAN to judge the platform endian configuration, but for newer version GCC, it seems `__BYTE_ORDER__&__ORDER_LITTLE_ENDIAN__&__ORDER_BIG_ENDIAN__` is a more compatible solution, you could check it here:gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html – Clock ZHONG Sep 05 '21 at 10:16
  • 1
    @Czipperz Thanks! I know how to show original code style in the comment now, I really didn't notice it before your remind. – Clock ZHONG Sep 05 '21 at 10:21
4

As of C++20, no more hacks or compiler extensions are necessary.

https://en.cppreference.com/w/cpp/types/endian

std::endian (Defined in header <bit>)

enum class endian
{
    little = /*implementation-defined*/,
    big    = /*implementation-defined*/,
    native = /*implementation-defined*/
};
  • If all scalar types are little-endian, std::endian::native equals std::endian::little

  • If all scalar types are big-endian, std::endian::native equals std::endian::big

Chris Uzdavinis
  • 6,022
  • 9
  • 16
2

You can't detect it at compile time to be portable across all compilers. Maybe you can change the code to do it at run-time - this is achievable.

pmod
  • 10,450
  • 1
  • 37
  • 50
1

It is not possible to detect endianness portably in C with preprocessor directives.

ouah
  • 142,963
  • 15
  • 272
  • 331
0

I took the liberty of reformatting the quoted text

As of 2017-07-18, I use union { unsigned u; unsigned char c[4]; }

If sizeof (unsigned) != 4 your test may fail.

It may be better to use

union { unsigned u; unsigned char c[sizeof (unsigned)]; }
pmg
  • 106,608
  • 13
  • 126
  • 198
0

As most have mentioned, compile time is your best bet. Assuming you do not do cross compilations and you use cmake (it will also work with other tools such as a configure script, of course) then you can use a pre-test which is a compiled .c or .cpp file and that gives you the actual verified endianness of the processor you're running on.

With cmake you use the TestBigEndian macro. It sets a variable which you can then pass to your software. Something like this (untested):

TestBigEndian(IS_BIG_ENDIAN)
...
set(CFLAGS ${CFLAGS} -DIS_BIG_ENDIAN=${IS_BIG_ENDIAN}) // C
set(CXXFLAGS ${CXXFLAGS} -DIS_BIG_ENDIAN=${IS_BIG_ENDIAN}) // C++

Then in your C/C++ code you can check that IS_BIG_ENDIAN define:

#if IS_BIG_ENDIAN
    ...do big endian stuff here...
#else
    ...do little endian stuff here...
#endif

So the main problem with such a test is cross compiling since you may be on a completely different CPU with a different endianness... but at least it gives you the endianness at time of compiling the rest of your code and will work for most projects.

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
0

I provided a general approach in C with no preprocessor, but only runtime that compute endianess for every C type.

the output if this on my Linux x86_64 architecture is:

fabrizio@toshibaSeb:~/git/pegaso/scripts$ gcc -o sizeof_endianess sizeof_endianess.c 
fabrizio@toshibaSeb:~/git/pegaso/scripts$ ./sizeof_endianess 
INTEGER TYPE  | signed  |  unsigned  | 0x010203...             | Endianess
--------------+---------+------------+-------------------------+--------------
int           |  4      |      4     | 04 03 02 01             | little
char          |  1      |      1     | -                       | -
short         |  2      |      2     | 02 01                   | little
long int      |  8      |      8     | 08 07 06 05 04 03 02 01 | little
long long int |  8      |      8     | 08 07 06 05 04 03 02 01 | little
--------------+---------+------------+-------------------------+--------------
FLOATING POINT| size    |
--------------+---------+
float         |  4
double        |  8
long double   | 16

Get source at: https://github.com/bzimage-it/pegaso/blob/master/scripts/sizeof_endianess.c

This is a more general approach is to not detect endianess at compilation time (not possibile) nor assume any endianess escludes another one. In fact is important to remark that endianess is not a concept of the architecture/processor but regards single type. As argued by @Christoph at https://stackoverflow.com/a/4712594/3280080 PDP-11 for example can have different endianess at the same time.

The approach consist to set an integer to be x = 0x010203... as long is it, then print them looking at casted-at-single-byte incrementing the address by one.

Can somebody test it please in a big endian and/or mixed endianess ?

bzimage
  • 71
  • 1
  • 5
-1

I know I'm late to this party, but here is my take.

int is_big_endian() {
    return 1 & *(uint16_t*)"01";
}

This is based on the fact that '0' is 48 in decimal and '1' 49, so '1' has the LSB bit set, while '0' not. I could make them '\x00' and '\x01' but I think my version makes it more readable.

Garmekain
  • 664
  • 5
  • 18
  • 1
    An important question is, can this version be optimized away by compiler ? Answer is : mostly yes, although not as well as a numerical version : https://godbolt.org/g/GhtEYW – Cyan Jul 18 '17 at 22:34
  • 3
    Interesting idea, yet can violate alignment requirements of `uint16_t`. (it is UB code for some embedded processors). – chux - Reinstate Monica Oct 09 '17 at 19:47
-6
#define BIG_ENDIAN ((1 >> 1 == 0) ? 0 : 1)
musefan
  • 47,875
  • 21
  • 135
  • 185
kranius
  • 1
  • 1
  • 1
    How does this detect endianness? – sharptooth Jan 24 '12 at 11:01
  • with the byte shift. 1 >> 1 is 0 on a little endian arch. (the bit get lost after shifting, thus it evals to 0). one could warp this into an enum for readability. – kranius Jan 24 '12 at 11:05
  • 4
    Great, but the same will happen on any endianness. Endianness is how the data is stored, not how the shift is done. – sharptooth Jan 24 '12 at 11:06
  • little endian: 1 is 0000 00001, after shift it's 0000 0000 big endian: 1 is 0001 0000, after shift it's 0000 1000 Am I wrong ? – kranius Jan 24 '12 at 11:16
  • 2
    That's how bytes are stored in memory, but manipulation is not done byte-wise, it is done on the number as a whole which is endianness-agnostic. – sharptooth Jan 24 '12 at 11:19
  • same comment, i'm afraid it does not work. For unsigned numbers, ">> 1" is equal to "/ 2", whatever endianess. – Cyan Jan 24 '12 at 12:37