Detecting Byte Order of a System

From Software Engineers Wiki
Jump to: navigation, search

How to detect endianness (byte order) of a system?

Answer #1

There are two different byte ordering.

  • Little-endian: increasing numeric significance with increasing memory addresses. LSB (Least Significant Byte) is stored in lower address.
  • Big-endian: decreasing numeric significance with increasing memory addresses. MSB (Least Significant Byte) is stored in lower address.

For example, in 32 bit system, 0x12345678 is stored in different way.

  • Little-endian: 0x78 0x56 0x34 0x12
  • Big-endian: 0x12 0x34 0x56 0x78

Using this feature we can detect endianness in following way.

#include <stdio.h>
#include <stdint.h>

int main(void)
{
        uint32_t val = 0x12345678;
        uint8_t *p8 = (uint8_t *) &val;

        if (*p8 == 0x78)
                printf("Little endian\n");
        else if (*p8 == 0x12)
                printf("Big endian\n");

        return 0;
}

Answer #2: Using gcc predefined macros

When the compiler generates code, it needs to know the endianness of target system. It can be specified via compiler options in case of GCC.

  • -mlittle-endian
  • -mbig-endian

In source code level, it can detect the compiler setting. (It is possible that compiler setting could be wrong, but in that case, built binary won't run on target). Here is the way to detect compiler setting.

#include <stdio.h>

int main(void)
{
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
        printf("Little endian\n");
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
        printf("Big endian\n");
#endif

        return 0;
}

Reference

Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox