在http://blog.csdn.net/wwyyxx26/article/details/6092276里介绍了一下位域,今天又遇到了位域的大小端的问题,这里做点记录
首先这里有字节间的大小端问题和一个字节内bit位的大小端问题
如下的描述是在linux x64上上编译出的结果
struct st_s
{
int a1 : 1;
int a2 : 1;
int a3 : 1;
int a4 : 1;
int a5 : 1;
int a6 : 1;
int a7 : 1;
int a8 : 1;
int b : 8;
int c : 8;
int d : 8;
};
union st_u
{
struct st_s;
int n;
};
高---低
对a8赋值1得到n值为128,那么二进制布局如下:
00000000 00000000 00000000 1 0 0 0 0 0 0 0
d c b a8 a1
struct st_s
{
int a1 : 1;
int a2 : 1;
int a3 : 1;
int a4 : 1;
int a5 : 1;
int a6 : 1;
int a7 : 2;
int b : 8;
int c : 8;
int d : 8;
};
对a7赋值1得到n值为64
00000000 00000000 00000000 01 0 0 0 0 0 0
d c b a7 a1
以上是主机字节顺序时的布局
另外值得注意的是网络字节顺序时和主机字节顺序时的转换问题,例如,如下的数据是一个ps流的包头,是网络字节顺序的
00 00 01 BA 4C4F8D8F 94 01000003 FE FF FF 00 00 00 01
4C(01 001 1 00) 01是固定的值(fix_bit),001是system_clock_reference_base1, 1是marker_bit,00是system_clock_reference_base21
4F(01001111) system_clock_reference_base22
8D(10001 1 01) 10001是system_clock_reference_base23,1是marker_bit,01是system_clock_reference_base31
8F(10001111) system_clock_reference_base32
94(10010 1 00)10010是system_clock_reference_base33,1是marker_bit2, 最后2个0是system_clock_reference_extension1
01(0000000 1)
00(00000000) program_mux_rate
00(00000000)
03(000000 11) 最后两个0是两个marker_bit
FE(11111 110) 保留位 110(pack_stuffing_length)说明有6个字节的填充字节
对应到主机字节顺序的结构体如下
struct st_program_stream_pack_header
{
//4个字节
unsigned char pack_start_code[4];
//一个字节
unsigned char system_clock_reference_base21:2; //时钟参考
unsigned char marker_bit:1;
unsigned char system_clock_reference_base1:3; //时钟参考
unsigned char fix_bit:2;//'01'
//一个字节
unsigned char system_clock_reference_base22; //时钟参考
//一个字节
unsigned char system_clock_reference_base31:2;
unsigned char marker_bit1:1;
unsigned char system_clock_reference_base23:5;
//一个字节
unsigned char system_clock_reference_base32;
//一个字节
unsigned char system_clock_reference_extension1:2;
unsigned char marker_bit2:1;
unsigned char system_clock_reference_base33:5;//system_clock_reference_base 33bit
//一个字节
unsigned char marker_bit3:1;
unsigned char system_clock_reference_extension2:7; //system_clock_reference_extension 9bit
//一个字节
unsigned char program_mux_rate1;
//一个字节
unsigned char program_mux_rate2;
//一个字节
unsigned char marker_bit5:1;
unsigned char marker_bit4:1;
unsigned char program_mux_rate3:6;
//一个字节
unsigned char pack_stuffing_length:3;
unsigned char reserved:5;
};