是否有一种编程方法来检测您使用的是大端序还是小端序体系结构?我需要能够编写将在英特尔或PPC系统上执行的代码,并使用完全相同的代码(即,没有条件编译)。


当前回答

要了解更多细节,你可能想要查看这篇codeproject文章Endianness的基本概念:

如何在运行时动态测试Endian类型? 正如《计算机》中解释的那样 动画FAQ,可以使用 下面的函数看看你的代码 是在小端还是大端运行 系统:崩溃 定义BIG_ENDIAN 0 #定义LITTLE_ENDIAN

int TestByteOrder()
{
   short int word = 0x0001;
   char *byte = (char *) &word;
   return(byte[0] ? LITTLE_ENDIAN : BIG_ENDIAN);
}

这段代码将值0001h赋给a 16位整数。然后是char指针 第一次分配给点 的(最低有效)字节 整数值。的第一个字节 整数是0x01h,然后系统 是Little-Endian (0x01h在 最低或最不重要, 地址)。如果是0x00h,则 系统是大端的。

其他回答

我会这样做:

bool isBigEndian() {
    static unsigned long x(1);
    static bool result(reinterpret_cast<unsigned char*>(&x)[0] == 0);
    return result;
}

沿着这些思路,您将得到一个只进行一次计算的省时函数。

c++的方法是使用Boost,在Boost中,预处理器检查和类型转换被划分到经过非常彻底测试的库中。

Predef库(boost/ Predef .h)识别四种不同的字节序。

end - dian库计划提交给c++标准,支持对end -sensitive数据的各种操作。

正如前面的回答所述,Endianness将成为c++ 20的一部分。

这是未经测试的,但在我看来,这应该是可行的。因为在小端序上是0x01,在大端序上是0x00。

bool runtimeIsLittleEndian(void)
{
    volatile uint16_t i=1;
    return ((uint8_t*)&i)[0]==0x01; // 0x01=little, 0x00=big
}

参见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;
} 
int i=1;
char *c=(char*)&i;
bool littleendian=c;