是否有一种编程方法来检测您使用的是大端序还是小端序体系结构?我需要能够编写将在英特尔或PPC系统上执行的代码,并使用完全相同的代码(即,没有条件编译)。
当前回答
这是未经测试的,但在我看来,这应该是可行的。因为在小端序上是0x01,在大端序上是0x00。
bool runtimeIsLittleEndian(void)
{
volatile uint16_t i=1;
return ((uint8_t*)&i)[0]==0x01; // 0x01=little, 0x00=big
}
其他回答
你也可以通过预处理器使用Boost头文件来做到这一点,这可以在Boost endian中找到。
int i=1;
char *c=(char*)&i;
bool littleendian=c;
除非你使用的框架已经移植到PPC和英特尔处理器上,否则你将不得不进行条件编译,因为PPC和英特尔平台拥有完全不同的硬件架构、管道、总线等。这使得两者的程序集代码完全不同。
至于查找字节序,请执行以下操作:
short temp = 0x1234;
char* tempChar = (char*)&temp;
您可以让tempChar为0x12或0x34,从中可以知道字节序。
参见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;
}
我会这样做:
bool isBigEndian() {
static unsigned long x(1);
static bool result(reinterpret_cast<unsigned char*>(&x)[0] == 0);
return result;
}
沿着这些思路,您将得到一个只进行一次计算的省时函数。
推荐文章
- 如何构建和使用谷歌TensorFlow c++ api
- 使嵌套JavaScript对象平放/不平放的最快方法
- 大的Ө符号到底代表什么?
- 堆与二叉搜索树(BST)
- 给定一个数字数组,返回所有其他数字的乘积的数组(不除法)
- 断言是邪恶的吗?
- 下面这些短语在c++中是什么意思:0 -,default-和value-initialization?
- 广度优先Vs深度优先
- 在STL地图中,使用map::insert比[]更好吗?
- C++ Linux的想法?
- 如何为Fedora安装g++ ?
- Std::cin输入空格?
- c++标准是否要求iostreams的性能很差,或者我只是在处理一个糟糕的实现?
- gcc在哪里查找C和c++头文件?
- 为什么我们需要require require ?