是否有一种编程方法来检测您使用的是大端序还是小端序体系结构?我需要能够编写将在英特尔或PPC系统上执行的代码,并使用完全相同的代码(即,没有条件编译)。
当前回答
这是未经测试的,但在我看来,这应该是可行的。因为在小端序上是0x01,在大端序上是0x00。
bool runtimeIsLittleEndian(void)
{
volatile uint16_t i=1;
return ((uint8_t*)&i)[0]==0x01; // 0x01=little, 0x00=big
}
其他回答
这是未经测试的,但在我看来,这应该是可行的。因为在小端序上是0x01,在大端序上是0x00。
bool runtimeIsLittleEndian(void)
{
volatile uint16_t i=1;
return ((uint8_t*)&i)[0]==0x01; // 0x01=little, 0x00=big
}
我很惊讶没有人提到预处理器默认定义的宏。但这取决于你的平台;它们比你自己写尾票要干净得多。
例如;如果我们看看GCC定义的内置宏(在x86-64机器上):
:| gcc -dM -E -x c - | grep -i endian
#define __LITTLE_ENDIAN__ 1
在PPC机器上,我得到:
:| gcc -dM -E -x c - | grep -i endian
#define __BIG_ENDIAN__ 1
#define _BIG_ENDIAN 1
(The:| gcc - dm - e -x c - magic打印出所有内置宏。)
如果你不想要条件编译,你可以写独立的代码。下面是一个例子(摘自Rob Pike):
以独立于端序的方式读取磁盘上以little-endian方式存储的整数:
i = (data[0]<<0) | (data[1]<<8) | (data[2]<<16) | (data[3]<<24);
同样的代码,试图考虑到机器的字节顺序:
i = *((int*)data);
#ifdef BIG_ENDIAN
/* swap the bytes */
i = ((i&0xFF)<<24) | (((i>>8)&0xFF)<<16) | (((i>>16)&0xFF)<<8) | (((i>>24)&0xFF)<<0);
#endif
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");
这是另一个解。类似于Andrew Hare的解决方案。
参见Endianness - c级代码说明。
// assuming target architecture is 32-bit = 4-Bytes
enum ENDIANNESS{ LITTLEENDIAN , BIGENDIAN , UNHANDLE };
ENDIANNESS CheckArchEndianalityV1( void )
{
int Endian = 0x00000001; // assuming target architecture is 32-bit
// as Endian = 0x00000001 so MSB (Most Significant Byte) = 0x00 and LSB (Least Significant Byte) = 0x01
// casting down to a single byte value LSB discarding higher bytes
return (*(char *) &Endian == 0x01) ? LITTLEENDIAN : BIGENDIAN;
}