CPU的大小端问题

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

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 <stdio.h>
#include <stdio.h>

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值