c/c++中结构体中的位域在大小端设备上的内存存储方式----------位域

结构体

typedef struct Time
{
    unsigned int second        :6;                    //    秒    0-59
    unsigned int minute        :6;                    //    分    0-59
    unsigned int hour          :5;                    //    时    0-23
    unsigned int day           :5;                    //    日    1-31
    unsigned int month         :4;                    //    月    1-12
    unsigned int year          :6;                    //    年    2000-2063
}Time;

 1. 小端设备(低字节在内存的低地址)

Time t;
memset((void *)(&t), 0x0, sizeof(t));
t.year = 1;
t.month = 2;
t.day = 3;
t.hour = 4;
t.minute = 5;
t.second = 6;

内存地址:高--->低

0x04864146

----------------------------------------------------------------------------------------

year     |  month  |  day      |  hour  |   minute  |  second
0000 01 00,10 00 011 0,0100 0001,01 00 0110
1 2 3 4 5 6

----------------------------------------------------------------------------------------

 总结:

结构体中的位域成员,按照成员的顺序, 先定义的成员分配在所占内存的低位地址,后定义的的成员分配在所占内存的高位地址;

如,先定义的second成员存放在四个字节中的最低的地址,最后定义的year成员存放在四个字节中的最高地址;

2.大端设备

Time t;
memset((void *)(&t), 0x0, sizeof(t));
t.year = 1;
t.month = 2;
t.day = 3;
t.hour = 4;
t.minute = 5;
t.second = 6;

内存地址:高--->低

0x18520c81

----------------------------------------------------------------------------------------

second   |  minute  |  hour      |  day  |   month  |  year
0001 10 00,0101 0010,0 000,11 00,10 00 0001
6       5 4 3 2 1

----------------------------------------------------------------------------------------

总结:

按照结构体成员的顺序, 先定义的成员分配在高地址,后定义的的成员分配在低地址,

如先定义的second成员存放在最高的地址,最后定义的year成员存放在最低地址;

在大端设备上定义一个位域成员相反的结构体(相对于小端设备的结构体),如:

原文地址:https://www.cnblogs.com/weiyouqing/p/13600535.html