关于big-endian和little-endian小程序

来源:互联网 发布:php 源码 owncloud 编辑:程序博客网 时间:2024/04/30 14:17

之前在笔试的时候,老会遇到被写各种小的代码,big endian 和 little endian就是其中之一。使用union实现非常方便。


#include <stdio.h>
int main(){
        union{
                short s;
                char str[2];
        } test;
        test.s = 0x0102;
        if(sizeof(short)==2){
                if(test.str[0]==1&&test.str[1]==2)
                        printf("big-endian\n");
                else if(test.str[0]==2&&test.str[1]==1)
                        printf("little-endian\n");
                else
                        printf ("unknown type\n");
        }else
                printf("sizeof(short)=%d",sizeof(short));
        return 0;
}



0 0