使用联合体中,变量保存的位置,来判断当前环境是大端还是小端序
/*
* Copyright (c) Huawei Technologies Co., Ltd. 2019-2020. All rights reserved.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
void byteOrder()
{
signed int a;
union {
short date;
char value[2];
} test;
test.date = 0x0102;
if (test.value[0] == 0x01 && test.value[1] == 0x02) {
printf("Bid endian\n");
} else if (test.value[0] == 0x02 && test.value[1] == 0x01) {
printf("Little endian\n");
} else {
printf("none");
}
}
int main(int argc, const char *argv[])
{
byteOrder();
return 0;
}