大家好 我正在做一些初步检查,看看我的系统是大端还是小端。 在 LInux 中,默认情况下它应该是 little-endian,但我只是想仔细检查一下。 我使用了两种方法
- 使用 boost endian 支持
- 使用我在网上找到的一些代码
我使用了下面的静态断言
BOOST_STATIC_ASSERT(!BIG_ENDIAN);
在编译期间失败了,所以我虽然..mmhh...我的系统是big endian吗? 这是我的错误
error: invalid application of ‘sizeof’ to incomplete type
boost::STATIC_ASSERTION_FAILURE<false>’
如果我使用类似下面的代码进行测试,它会确认系统是小端。 你知道我做错了什么吗?我是否正确使用了 Boost 宏?
bool is_big_endian_v3(){ long x = 0x34333231; char *y = (char *) &x; if(std::strncmp(y,"1234",4)){ printf("Big Endian"); return true; }else{ printf("Little Endian"); return false; } std::runtime_error ex("I cannot be here"); throw ex; }
最佳答案
Boost 库已更改,之前答案中的代码现在(2019 年 7 月)生成弃用消息并提出以下建议:
#include <boost/predef/other/endian.h>
#include <stdlib.h>
#include <iostream>
int main()
{
#if BOOST_ENDIAN_BIG_BYTE
std::cout << "Big endian." << std::endl;
#elif BOOST_ENDIAN_LITTLE_BYTE
std::cout << "Little endian." << std::endl;
#else
std::cout << "Unknown endian." << std::endl;
#endif
exit(EXIT_SUCCESS);
}
关于c++ - 与小代码的结果相比,boost 的字节序检查不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4345341/