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

Reference:

  1. How to check whether a system is big endian or little endian?
  2. C program to check little vs. big endian
  3. Process byte order -- big endian-or little endian

Method 1:

int n = 1;                              // if 32 bit system, n = 0x00000001

if(*(char *)&n == 1) 
    printf("little endian");
else
    printf("big endian");

If it is little endian, , the n in the memory will be something like:

    higher memory
      ----->
+----+----+----+----+
|0x01|0x00|0x00|0x00|
+----+----+----+----+
A
|
&n

If it is big endian, , the n in the memory will be something like:

    higher memory
      ----->
+----+----+----+----+
|0x00|0x00|0x00|0x01|
+----+----+----+----+
A
|
&n

Method 2:

union
{
    int a;
    char b;
}EndianTest;

int main()
{
    EndianTest.a=1;                     // if 32 bit system, EndianTest.a = 0x00000001
    if(EndianTest.b  = 0x01)
        printf("little endian");
    else
        printf("big endian");
    return 0;
}

results matching ""

    No results matching ""