CPU的大小端问题

1> 如何判断一个板子的cpu 是big-endian 还是 Little-endian的?    big-endian与little-endian
判断endian :
#include
#include

int main(void)
{
       short int a = 0x1234;
       char *p = (char *)&a;
       printf("p=%#hhx/n",*p);
      
       if(*p == 0x34)
           printf("Little endian /n");
       else if(*p == 0x12)
           printf("Big endian /n");
       else
           printf("Unknow endian /n");  
       return 0;
}

2> little to big or big to little endian
#include
#include

typedef unsigned int u32;
typedef unsigned short u16;

#if 0
//simple: not check varible types
        #define BSWAP_16(x)         ( (((x) & 0x00ff) << 8 ) | (((x) & 0xff00) >> 8 )  )
//complex:check varible types
#else
        #define BSWAP_16(x)         (u16) ( ((((u16)(x)) & 0x00ff) << 8 ) | ((((u16)(x)) & 0xff00) >> 8 ) )
#endif

#define BSWAP_32(x)     (u32) ( (( ((u32)(x)) & 0xff000000 ) >> 24) | (( ((u32)(x)) & 0x00ff0000 ) >> 8 ) |  / (( ((u32)(x)) & 0x0000ff00 ) << 8 ) | (( ((u32)(x)) & 0x000000ff ) << 24) )

u16 bswap16(u16 x)
{
       return (x & 0x00ff) << 8 | (x & 0xff00) >> 8  ;
}

u32 bswap32(u32 x)
{
       return       ( x & 0xff000000 ) >>24 | ( x & 0x00ff0000 ) >>8 | ( x & 0x0000ff00 ) <<8 |( x & 0x000000ff ) << 24  ;
}

int main(void)
{      
      u16 var_short = 0x1234;
      u32 var_int = 0x1234567890;

      printf("macro conversion:%#x/n",BSWAP_16(0x123490 ));     //要能正确转换
      printf("macro conversion:%#x/n", BSWAP_32(0x1234567890)); //要能正确转换
      printf("-----------------/n");
     
      printf("function conversion:%#x/n",bswap16(0x123490));
      printf("function conversion:%#x/n", bswap32(0x1234567890)); 

      return 0;
}

实现同样的功能,我们来看看Linux 操作系统中相关的源代码是怎么做的:

  1. static union { char c[4]; unsigned long mylong; } endian_test = {{ 'l''?''?''b' } };  
  2. #define ENDIANNESS ((char)endian_test.mylong)  

Linux 的内核作者们仅仅用一个union 变量和一个简单的宏定义就实现了一大段代码同样的功能!由以上一段代码我们可以深刻领会到Linux 源代码的精妙之处!

(如果ENDIANNESS=’l’表示系统为little endian,为’b’表示big endian )。


其中关于printf()中"%#x"和"%hhx"请参考网址:(http://blog.csdn.net/striver1205/article/details/7477868)

你可能感兴趣的:(C/C++)