以0x01234567爲例
大端法(big endian) : 最高有效字節在最前面
地址 | 值 |
---|---|
0x100 | 0x01 |
0x101 | 0x23 |
0x102 | 0x45 |
0x103 | 0x67 |
小端法(big endian) : 最低有效字節在最前面。大多數Intel兼容機器爲小段機。
地址 | 值 |
---|---|
0x100 | 0x67 |
0x101 | 0x45 |
0x102 | 0x23 |
0x103 | 0x01 |
以下可以測試機器是大端還是小端。
static union
{
char c[4];
unsigned long mylong;
} endian_test = {{'l','?','?','b'}};
#define ENDIANNESS ((char)endian_test.mylong)
地址 | 大端機 | 小端機 |
---|---|---|
0x100 | b | l |
0x101 | ? | ? |
0x102 | ? | ? |
0x103 | l | b |
宏
求一個結構體struct裏某個變量相對於struct的偏移量
{
int a;
char b[20];
double ccc;
}
#define FIND(struc, e) (size_t)&(((struc*)0)->e)
// (struc*)0 將0強制轉換爲struc*,即爲指向struct的指針
// &((struc*)0)->e 表示取結構體中e的地址
// 因爲首地址爲0,則e的地址即爲偏移量
FIND(student, a); //0
FIND(student, b); //4