bigendian,littleendian

in #tech7 years ago

概述

在计算机内存存储模型中,cpu读取内存分为两种类型,bigendian和littleendian两种,两种的主要区别为,针对同一数据,在内存中的高位存储数据的高位还是低位,例如:
对于十六进制数 0x6162abcd

  • bigendian
    内存低位 0x61 0x62 0xab 0xcd 高位内存

  • littleednian
    内存低位 0xcd 0xab 0x62 0x61 高位内存

通常我们使用的x86系列的cpu计算机使用的little-endian模式

如何判断计算机是big-endian模式还是little-endian模式

   int i =1;
  char *p = (char *)&i;
  if(*p = 1)
      printf("little endian");
  else
     printf("big endian");

要验证大小端,只需要知道计算机在存储数据的时候,低位存储的是低位的数据还是高位的数据,如果是低位的数据,则是little-endian,如果是高位的数据,则是big-endian。i至少占有2个字节的长度,char只有一个字节,当计算机是big-endian时,i的存储方式十六进制为 0x00 0x01,而little-endian则为 0x01 0x00,当把以上的第一个字节赋值给char,也就是p时,如果p=1,那么显然计算机就是little-endian的

其他例子:

/*return 1 则为little-endian ,反之则为其他
int checkCPUendian()
{
  union
{
  unsigned int a;
  unsigned char b;
}c;
c.a = 1;
return(c.b==1);
}

上面利用了联合体的内存共享特性,和第一个例子的原理一样

Linux操作系统内核实现方式:

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

Congratulations @bgping! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

You published your First Post

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

By upvoting this notification, you can help all Steemit users. Learn how here!

Coin Marketplace

STEEM 0.16
TRX 0.13
JST 0.027
BTC 58503.45
ETH 2594.59
USDT 1.00
SBD 2.45