大小端 位域

針對內核IP頭version 和 ihl在大小端異位的一些介紹:
 
version先定義的,應該在高位啊,即most significant 4 bits。

可以這樣來解釋,
1)從道理上來說,little endian中的位應該這樣排列:
01234567
即排在前面的是低位。因此,先分配least significant bits
2)而在Big endian中,位應該這樣排列:
76543210
即排在前面的是高位。因此,先分配most significant bits。

可以這樣來理解,
1)在Big Endian的情況下,"排在前面的是高位"
a. 對於順序的兩個字節來說,第一個字節是高位(排在前面),第二個字節是低位(排在後面)。
b. 對於字節內部的位來說,
-------most significant bits排在前面,是高位,
-------least significant bits排在後面,是低位。
2)在Little Endian的情況下,"排在前面的是低位"
a. 對於順序的兩個字節來說,第一個字節是低位(排在前面),第二個字節是高位(排在後面)。
b. 對於字節內部的位來說,
-------least significant bits排在前面,是低位,
-------most significant bits排在後面,是高位。

這樣,在對struct中的成員進行分配的時候,"按排列順序分配,先分配排在前面的"
1)big endian從高位向低位分配,
a. 對字節,是先分配低地址的字節,再分配高地址的字節。
b. 對位域,先分配most significant bits,再分配least significant bits。
1)little endian從低位向高位分配,
a. 對字節,是先分配低地址的字節,再分配高地址的字節。
b. 對位域,先分配least significant bits,再分配most significant bits。

======================================

以上說的都是分配的順序。

對於IP協議來說,
1)IP's byte order is big endian.
2)The bit endianness of IP inherits that of the CPU,
3)and the NIC takes care of converting it from/to the bit transmission/reception order on the wire.

並且,按照IP協議,
1)"version" is the most significant four bits of the first byte of an IP header.
2)"ihl" is the least significant four bits of the first byte of the IP header.

也就是說,version必須分配在most significant four bits,
按照上面說的分配順序,在big endian中,version必須放在前面。

#include <stdio.h>
int main()
{
char* c;
struct bitfield {
int ia:3;
int ib:2;
int ic:3;
} field;
field.ia=4;
field.ib=2;
field.ic=2;

c=(char *) &field;
printf("%d ",*c);
return 0;
}
>在對struct中的成員進行分配的時候,"按排列順序分配,先分配排在前面的"

struct 排列成 100 10 010

>1)little endian從低位向高位分配,
>b. 對位域,先分配least significant bits,再分配most significant bits。

按照字面上理解,分配後成 010 01 001 (76543210) 實際上是 010 10 100

所以:先分配 least significant 3 bits,再分配middle 2 bits,最後分配most significant 3 bits。

就像這樣:

>1)"version" is the most significant 4 bits of the first byte of an IP header.
>2)"ihl" is the least significant 4 bits of the first byte of the IP header.
 
所謂的“對位域,先分配least significant bits,再分配most significant bits”
並不是說分配是bit by bit的,而是根據結構的定義,以結構成員爲單位,一組一組地,依次分配到位組。

ia=100排在最前面,因此作爲一組,分配到least significant 3 bits,
ib=10排在中間,因此作爲一組,分配到接下來的middle 2 bits,
ic=010排在最後面,因此作爲一組,分配到most significant 3 bits。

 

發佈了9 篇原創文章 · 獲贊 2 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章