Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1581850
  • 博文数量: 92
  • 博客积分: 2002
  • 博客等级: 大尉
  • 技术积分: 4717
  • 用 户 组: 普通用户
  • 注册时间: 2010-09-01 17:09
文章分类

全部博文(92)

文章存档

2013年(1)

2012年(6)

2011年(85)

分类: LINUX

2011-10-17 13:33:44

 判断字节序大小端的程序
  1. #include "stdio.h"
  2. #include "unistd.h"

  3. /************ 最简单方式 *********/
  4. static union {
  5.     char c[4];
  6.     unsigned long l;
  7. } endian_test = {
  8.     { 'l', '?', '?', 'b' }
  9. };

  10. #define ENDIANNESS ((char)endian_test.l)
  11. /*************************/

  12. int main(void)
  13. {
  14.     union{
  15.         short s;
  16.         char c[sizeof(short)];
  17.     } un;
  18.     
  19.     un.s = 0x0102;

  20.     if(sizeof(short) == 2){
  21.         printf("%02x\n",un.c[0]);
  22.         printf("%02x\n",un.c[1]);
  23.         if(un.c[0] == 1 && un.c[1] == 2)
  24.             printf("big-endian\n");
  25.         else if(un.c[0] == 2 && un.c[1] == 1)
  26.             printf("little-endian\n");
  27.         else
  28.             printf("unknown\n");
  29.     }
  30.     else
  31.         printf("sizeof(short)=%d\n",sizeof(short));
  32.             
  33.     return 0;    
  34. }

对于上层应用程序,如果你总是直接对内存进行char操作,即一个字节一个字节的操作,没字节序问题
当使用的基本数据类型的大小多于一个字节时,如int,就有字节序的问题了
比如同样一个数字0x0102,不同字节序的平台,内存存储方式不一样

字节序       低-高 地址
大端         01 02
小端         02 01







内核编程时,也要考虑大小端问题。

  1. struct iphdr {
  2. #if defined(__LITTLE_ENDIAN_BITFIELD)
  3.     __u8 ihl:4,
  4.         version:4;
  5. #elif defined (__BIG_ENDIAN_BITFIELD)
  6.     __u8 version:4,
  7.         ihl:4;
  8. #else
  9. #error "Please fix "
  10. #endif
  11.     __u8 tos;
  12.     __be16 tot_len;
  13.     __be16 id;
  14.     __be16 frag_off;
  15.     __u8 ttl;
  16.     __u8 protocol;
  17.     __sum16 check;
  18.     __be32 saddr;
  19.     __be32 daddr;
  20.     /*The options start here. */
  21. };

---------------------------------------- 华丽的分割线 -------------------------------------

       高位             低位
大端   bit0             bit32
小端   bit32            bit0

datasheet是这样子的吗?
阅读(4048) | 评论(0) | 转发(1) |
0

上一篇:PowerPC的MMU初始化

下一篇:DDR配置备忘录

给主人留下些什么吧!~~