How to check whether a system is big endian or little endian?

How to check whether a system is big endian or little endian?


Solution 1:

In C, C++

int n = 1;
// little endian if true
if(*(char *)&n == 1) {...}

See also: Perl version

Solution 2:

In Python:

from sys import byteorder
print(byteorder)
# will print 'little' if little endian

Solution 3:

Another C code using union

union {
    int i;
    char c[sizeof(int)];
} x;
x.i = 1;
if(x.c[0] == 1)
    printf("little-endian\n");
else    printf("big-endian\n");

It is same logic that belwood used.