以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