本帖最后由 hxlwjn 于 2010-4-21 10:14 编辑
最近在学习Linux,发现源代码里不少结构体都用到位段,但我觉得使用位段并没有优势,虽然节省了一些数据空间,但给位段赋值需要更多的指令,不但代码空间不会减少,而且还增加了执行时间。看下面的例子:
1.不使用位段
struct test
{
unsigned int a;
unsigned int b;
unsigned int c;
};
int main()
{
struct test temp;
unsigned char n=sizeof(temp);
temp.a=6;
temp.b=8;
temp.c=18;
}
keil uVision4 里面编译的汇编代码是:
11: struct test temp;
0x000000E0 E24DD00C SUB R13,R13,#0x0000000C
12: unsigned char n=sizeof(temp);
0x000000E4 E3A0100C MOV R1,#0x0000000C
13: temp.a=6;
0x000000E8 E3A00006 MOV R0,#0x00000006
0x000000EC E58D0000 STR R0,[R13]
14: temp.b=8;
0x000000F0 E3A00008 MOV R0,#0x00000008
0x000000F4 E58D0004 STR R0,[R13,#0x0004]
15: temp.c=18;
0x000000F8 E3A00012 MOV R0,#0x00000012
0x000000FC E58D0008 STR R0,[R13,#0x0008]
2.使用位段
struct test
{
unsigned int a:6;
unsigned int b:8;
unsigned int c:18;
};
int main()
{
struct test temp;
unsigned char n=sizeof(temp);
temp.a=6;
temp.b=8;
temp.c=18;
}
11: unsigned char n=sizeof(temp);
0x000000E4 E3A01004 MOV R1,#0x00000004
12: temp.a=6;
0x000000E8 E59D0000 LDR R0,[R13]
0x000000EC E3C0003F BIC R0,R0,#0x0000003F
0x000000F0 E3800006 ORR R0,R0,#0x00000006
0x000000F4 E58D0000 STR R0,[R13]
13: temp.b=8;
0x000000F8 E59D0000 LDR R0,[R13]
0x000000FC E3C00DFF BIC R0,R0,#0x00003FC0
0x00000100 E3800C02 ORR R0,R0,#0x00000200
0x00000104 E58D0000 STR R0,[R13]
14: temp.c=18;
0x00000108 E59D0000 LDR R0,[R13]
0x0000010C E1A00900 MOV R0,R0,LSL #18
0x00000110 E1A00920 MOV R0,R0,LSR #18
0x00000114 E3800912 ORR R0,R0,#0x00048000
0x00000118 E58D0000 STR R0,[R13]
那么,为什么还要使用位段呢? |