大小端

举个例子来说名大小端:  比如一个int x, 地址为0x100, 它的值为0x1234567. 则它所占据的0x100, 0x101, 0x102, 0x103地址组织如下图:

        0x01234567的MSB为0x01, LSB为0x67. 0x01在低地址(或理解为"MSB出现在LSB前面,因为这里讨论的地址都是递增的), 则为大端; 0x67在低地址则为小端.

认清这样一个事实: C中的数据类型都是从内存的低地址向高地址扩展,取址运算"&"都是取低地址.

两个测试Bit Endian的小程序


method_1

#include <stdio.h>

int main(int argc, char *argv[])
{

  int c = 1;
  if ((*(char *)&c) == 1) {
    printf("little endian/n");
  }
  else
    printf("big endian");

  return 0;
}

        int c 在内存中的表达为: 0x 00 000001 . (这里假设int为4字节). 用char可以截取一个字节. LSB为0x01, 若它出现在c的低地址, 则为小端.

method_2

#include <stdio.h>

int main(void)
{
/* Each component to a union type is allocated storage at the beginning of the union */
         
  union {
    short n;
    char c[sizeof(short)];
  }un;
 
  un.n = 0x01 02 ;
 
  if ((un.c[0] == 1 && un.c[1] == 2))
    printf("big endian/n");
  else if ((un.c[0] == 2 && un.c[1] == 1))
    printf("little endian/n");
  else
    printf("error!/n");
  return 0;
}

      
        union中元素的起始地址都是相同的——位于联合的开始. 用char来截取感兴趣的字节.      

区分大端与小端有什么用呢? 如果两个不同Endian的机器进行通信时, 就有必要区分了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值