Chinaunix首页 | 论坛 | 博客
  • 博客访问: 57171
  • 博文数量: 19
  • 博客积分: 1410
  • 博客等级: 上尉
  • 技术积分: 190
  • 用 户 组: 普通用户
  • 注册时间: 2008-10-03 15:03
文章分类
文章存档

2011年(1)

2009年(8)

2008年(10)

我的朋友

分类: LINUX

2008-10-20 14:53:36

一:判断大小端的2种方法
#include

int is_little_endian(void)
{
  unsigned short flag = 0x1234;
 
  if(*(unsigned char *)&flag == 0x34)
    return 1;
  else
    return 0; 
}

int main(int argc, char* argv[])
{
 union endian_un
{
 short var;
 char bits[sizeof(short)];
};

 union endian_un flag;
 flag.var = 0x0102;

 if(sizeof(short) == 2)
  {
   if(flag.bits[0] == 1 && flag.bits[1] == 2)
     printf("Judged by the first method,big_endian\n");
   else if(flag.bits[0] == 2 && flag.bits[1] == 1)
     printf("Judged by the first method,little_endian\n");
   else
     printf("Cann't judged the digtal\n");
  }
 
  if(is_little_endian())
    printf("Juged by the second method ,little_endian\n");
   else
    printf("Juged by the second method,big_endian\n");

 return 0;
}
二:转换大小端

#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 = 0x123490;

    
//u32 var_int = 0x1234567890;

    
//关键是要能对错误进行处理,给一个0x123490 照样能得出 0x9034的值,而且, 占内存要小的

    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;
}

阅读(1644) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~