用gcc使用位域的一些代码。

#include <stdio.h>
#pragma pack(1)

typedef struct {
    unsigned int one:24;
    unsigned int two:25;
    unsigned int three:23;
    unsigned int four:24;

} demo_type;

int main(void)
{
    demo_type s;
    printf("sizeof demo_type = %u\n", sizeof(demo_type));
    unsigned a;
    a = s.two;
    return 0;
}
#pragma pack(1)是关闭了内存对齐
其中 a = s.two 对应汇编如下

17            a = s.two;
004013ae:   movzbl 0x13(%esp),%eax
004013b3:   mov 0x14(%esp),%edx
004013b7:   and $0x1ffff,%edx
004013bd:   shl $0x8,%edx
004013c0:   or %edx,%eax
004013c2:   mov %eax,0x1c(%esp)

如果s.two是24位的话,

004013b3:这条语句会变成movwbl,并且and那句就没有了。
内存对齐是个很麻烦的事情,不对齐的话会有意想不到的额外开销

posted on 2013-05-14 13:39  zcranberry  阅读(205)  评论(0编辑  收藏  举报

导航