是否有一种编程方法来检测您使用的是大端序还是小端序体系结构?我需要能够编写将在英特尔或PPC系统上执行的代码,并使用完全相同的代码(即,没有条件编译)。
当前回答
我正在阅读教科书《计算机系统:程序员的视角》,有一个问题是要确定这是由C程序编写的。
我使用指针的特性来这样做:
#include <stdio.h>
int main(void){
int i=1;
unsigned char* ii = &i;
printf("This computer is %s endian.\n", ((ii[0]==1) ? "little" : "big"));
return 0;
}
因为int占用4个字节,而char只占用1个字节。我们可以使用char指针指向值为1的int类型。因此,如果计算机是小端序的,则char指针所指向的char值为1,否则,其值应为0。
其他回答
你也可以通过预处理器使用Boost头文件来做到这一点,这可以在Boost endian中找到。
要了解更多细节,你可能想要查看这篇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,则 系统是大端的。
参见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;
}
如果你可以使用c++ 20编译器,比如GCC 8+或Clang 7+,你可以使用std::endian。
注意:std::endian从<type_traits>开始,但在2019年科隆会议上被移动到<bit>。GCC 8、Clang 7、8、9在<type_traits>, GCC 9+和Clang 10+在<bit>。
#include <bit>
if constexpr (std::endian::native == std::endian::big)
{
// Big-endian system
}
else if constexpr (std::endian::native == std::endian::little)
{
// Little-endian system
}
else
{
// Something else
}
我正在阅读教科书《计算机系统:程序员的视角》,有一个问题是要确定这是由C程序编写的。
我使用指针的特性来这样做:
#include <stdio.h>
int main(void){
int i=1;
unsigned char* ii = &i;
printf("This computer is %s endian.\n", ((ii[0]==1) ? "little" : "big"));
return 0;
}
因为int占用4个字节,而char只占用1个字节。我们可以使用char指针指向值为1的int类型。因此,如果计算机是小端序的,则char指针所指向的char值为1,否则,其值应为0。