大端法和小端法

引言

在计算机内存中,通常是以字节(Byte),也就是 8 个位(Bit)为基本存储单元(也有以 16 位为基本存储单元的)。对于跨越多个字节的数据类型(比如 int 长 4 个字节),如何在内存中对这些字节进行排序有两种常见的方法:大端法(Big-endian)和小端法(Little-endian)

【注】首先不管是大端法还是小端法存储,计算机在内存中存放数据的顺序都是从低地址到高地址,所不同的是首先取低字节的数据存放在低地址还是取高字节数据存放在低地址。

基本概念

高位放在低地址就是大端法

低位放在低地址就是小端法

例如0x0A0B0C0D的在大端和小端中的存放方式分别为:

程序验证

清单一:利用C里的联合类型

 1 #include<stdio.h>
 2 
 3 union MyUnion
 4 {
 5     int a;
 6     char c;
 7 };
 8 
 9 int main()
10 {
11     MyUnion mu;
12     mu.a = 0x0001;
13     if (mu.c == 1)   printf("small endian\n");
14     else  printf("big endian\n");
15 
16 
17     return 0;
18 }

清单二:利用指针

 1 #include<stdio.h>
 2 
 3 typedef unsigned char *byte_pointer;
 4 
 5 void show_bytes(byte_pointer start, size_t len)
 6 {
 7     size_t i;
 8     for (int i = 0; i < len; i++)
 9         printf(" %.2x", start[i]);
10     printf("\n");
11 }
12 
13 void show_int(int x)
14 {
15     show_bytes((byte_pointer)&x, sizeof(int));
16 }
17 
18 void show_float(float x)
19 {
20     show_bytes((byte_pointer)&x, sizeof(float));
21 }
22 void show_pointer(void *x)
23 {
24     show_bytes((byte_pointer)&x, sizeof(void *));
25 }
26 
27 void test_show_bytes(int val)
28 {
29     int ival = val;
30     float fval = (float)ival;
31     int *pval = &ival;
32     show_int(ival);
33     show_float(fval);
34     show_pointer(pval);
35 }
36 
37 int main()
38 {
39     int num = 0x1926;
40     test_show_bytes(num);
41 
42     return 0;
43 }

结语

大多数Inter兼容机只用小端法,Android和IOS也只用小端法;IBM和Oracle的大多数机器用大端法,但它们的制造的个人电脑使用的是Inter兼容的处理器,因此使用小端法。

令人吃惊的是,对于哪种字节顺序更合适这个问题,人们表现的非常情绪化,从它的名字来源就可看出

【“端”的起源】

术语“little endian(小端)”和“big endian(大端)”出自Jonathan Swift的《格列佛游记》一书,其中两个派别交战的原因仅仅因为一方认为要从较大的一端敲开鸡蛋,而另一方认为要从小的一端敲开鸡蛋。

在作者的那个年代,Swift是借此讽刺英国和法国之间的持续冲突(难道命名者也是借此讽刺大端法和小端法的矛盾,,,只是臆想,蒟蒻什么也没说

 

参考资料:

1、https://blog.csdn.net/zuyi532/article/details/8020712

2、https://blog.csdn.net/zuyi532/article/details/8020712

3、https://blog.csdn.net/u012861978/article/details/51906546

猜你喜欢

转载自www.cnblogs.com/lfri/p/10166406.html