参考链接有3种方式,以下为最容易的方式:
联合体是共享内存,在联合体重定义一个char类型,一个int类型,
给int数据赋值为1,根据char的值是否为1就可以判断大小端了;
若char类型为1,则为小端;
若char类型不为1,则为大端;
//判断大小端
static bool isLocalhostBigEndian(void)
{
union
{
int a;
char b;
} num;
num.a = 1;
qDebug()<<“Local byte order is” << ((num.b != 1) ? “big endian” : “little endian”);
return num.b != 1;
}
//将高低端数据反向
template <typename T>
static void reverseInteger(T& num)
{
static_assert(std::is_integral<T>::value, "Must be an integral type.");
static_assert((sizeof(T) == 4) || (sizeof(T) == 2) || (sizeof(T) == 1), "Integer must be 4, 2 or 1 byte(s).");
char * _byte = reinterpret_cast<char *>(&num);
for (unsigned int i=0; i<sizeof(T)/2; ++i)
{
char c = _byte[i];
_byte[i] = _byte[sizeof(T) - 1 - i];
_byte[sizeof(T) - 1 - i] = c;
}
}
测试代码:
void test()
{
//已知其他进程数据为小端
bool isBig_endian = isLocalhostBigEndian();
int value = 16777216;
if(!isBig_endian )
reverseInteger(val);
//若为小端,则会打印出 1
qDebug()<<"========= value : "<<value;
}
int main()
{
test();
return 0;
}
参考:https:
//blog.csdn.net/qq_36391130/article/details/81944217