1. 程式人生 > >編譯時通過巨集__BYTE_ORDER判斷位元組序

編譯時通過巨集__BYTE_ORDER判斷位元組序

需要包含標頭檔案<endian.h>

該檔案通過引入<bits/endian.h>來定義__BYTE_ORDER

<endian.h>節選

/* Definitions for byte order, according to significance of bytes,
   from low addresses to high addresses.  The value is what you get by
   putting '4' in the most significant byte, '3' in the second most
   significant byte, '2' in the second least significant byte, and '1'
   in the least significant byte, and then writing down one digit for
   each byte, starting with the byte at the lowest address at the left,
   and proceeding to the byte with the highest address at the right.  */

#define __LITTLE_ENDIAN 1234
#define __BIG_ENDIAN    4321
#define __PDP_ENDIAN    3412

/* This file defines `__BYTE_ORDER' for the particular machine.  */
#include <bits/endian.h>


x86機器下的<bits/endian.h>檔案內容

/* i386 is little-endian.  */

#ifndef _ENDIAN_H
# error "Never use <bits/endian.h> directly; include <endian.h> instead."
#endif

#define __BYTE_ORDER __LITTLE_ENDIAN

mips機器下的<bits/endian.h>檔案內容

/* The MIPS architecture has selectable endianness.
   Linux/MIPS exists in two both little and big endian flavours and we
   want to be able to share the installed headerfiles between both,
   so we define __BYTE_ORDER based on GCC's predefines.  */

#ifndef _ENDIAN_H
# error "Never use <bits/endian.h> directly; include <endian.h> instead."
#endif

#ifdef __MIPSEB__
# define __BYTE_ORDER __BIG_ENDIAN
#else
# ifdef __MIPSEL__
#  define __BYTE_ORDER __LITTLE_ENDIAN
# endif
#endif

只要通過引入標頭檔案<endian.h>便可以在編譯時通過巨集判斷位元組序了

#if __BYTE_ORDER == __LITTLE_ENDIAN


#elif __BYTE_ORDER == __BIG_ENDIAN

#else
#error "Unknown byte order"
#endif