字节排序函数

来源:互联网 发布:eclipse修改端口号 编辑:程序博客网 时间:2024/05/15 23:55
    考虑一个16位的整数,它由2个字节组成。内存中存储这两个字节有两种方法:一种是将低字节存储在起始地址,这称为小端字节序;另一种方法是将高序字节存储在起始地址,这称为大端字节序。下面的程序可以检测是大端存储还是小端存储:

#include <stdio.h>int main(int argc, char *argv[]){    union
    {unsigned short num;unsigned char arr[sizeof(short)];    }test;    test.num = 0x0102;    if (sizeof(short) == 2)    {if (test.arr[0] == 1 && test.arr[1] == 2)printf("big endian\n");else if (test.arr[0] == 2 && test.arr[1] == 1)printf("little endian\n");elseprintf("unknown\n");    }    elseprintf("sizeof(short) = %d\n",sizeof(short));    exit(0);}


0 0