是否有一种编程方法来检测您使用的是大端序还是小端序体系结构?我需要能够编写将在英特尔或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。
其他回答
如果你可以使用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
}
请看这篇文章:
这里有一些代码来确定是什么 您的机器类型 Int num = 1; If (*(char *)&num == 1) { printf (" \ nLittle-Endian \ n "); } 其他的 { printf(“大端\ n”); }
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的解决方案。
bool isBigEndian()
{
static const uint16_t m_endianCheck(0x00ff);
return ( *((const uint8_t*)&m_endianCheck) == 0x0);
}
c++的方法是使用Boost,在Boost中,预处理器检查和类型转换被划分到经过非常彻底测试的库中。
Predef库(boost/ Predef .h)识别四种不同的字节序。
end - dian库计划提交给c++标准,支持对end -sensitive数据的各种操作。
正如前面的回答所述,Endianness将成为c++ 20的一部分。