write a macro to judge big endian or little endian

时间:2023-03-09 19:47:23
write a macro to judge big endian or little endian

Big endian means the most significant byte stores first in memory. int a=0x01020304, if the cpu is big endian, data are store 01 02 03 04 in memory in increasing address.

Below is a simple code to make the judgement.

//execute the following cmd on the command line,
//Judge the output, 1 for little endian, 0 for big endian
//echo -n I | od -o | head -n 1 | cut -f2 -d " " | cut -c 6
//1

#include <stdio.h>
#define IS_BIG_ENDIAN (*(short*)"\0\1" == (short)1)

int main()
{
if (IS_BIG_ENDIAN)
printf("the cpu is big endian\n");
else
printf("the cpu is small endian\n");
}