C语言判断机器大小端

#include <stdio.h>

// big_ending:      1
// little_ending:   2

int IsLittleEnding() {
    union {
        short value;
        char array[2];
    } u;
    u.value = 0x0102;
    if (u.array[0] == 1 && u.array[1] == 2) {
        return 1;
    }else if (u.array[0] == 2 && u.array[1] == 1) {
        return 2;
    }
    return -1;
}

int main() {
    int res;
    res = IsLittleEnding();
    printf("result is %d\n", res);
    if (res == 1) {
        printf("it is big ending");
    }
    if (res == 2) {
        printf("it is little ending");
    }
}
posted @ 2021-06-27 23:19  道友请留步W  阅读(95)  评论(0编辑  收藏  举报