前言
c语言,关于结构体位域中字节对齐的计算。
一、结构体位域是什么?
结构体位域是指在结构体中定义变量时使用 变量类型 变量名:位域 的方式定义,在使用位域后,该变量的大小就是位域的大小(bit)。
例如
struct test
{
int a:1;//变量a为1bit
int b:1;//变量b为1bit
};//sizeof(struct test ) 为 4
test里面的变量a占1位,b占一位,a和b共占2bit
因为int占4字节,按4字节对齐,所以test占4字节。
二、案例分析
1.代码部分
代码如下(示例):
#include<stdio.h>
//结构体中的位域字节对齐
struct test1
{
int a:8;
int b:4;
int c:4;
};
struct test2
{
/* data */
int a:2;
int b:1;
int c:1;
char d;
};
int main()
{
printf("test1=%ld\n",sizeof(struct test1));
printf("test2=%ld\n",sizeof(struct test2));
return 0;
}
下面分析s1:
test1中的成员各占
a 8bit
b 4bit
c 4bit
a+b+c 共2字节(8+4+4=16 16/8=2)
因为int占4字节,按4字节对齐,所以test1占4字节。
下面分析s2:
test2中的成员各占
a 2bit
b 1bit
c 1bit
d 1Byte
a+b+c共4位,但是因为int为最大字节类型,为4字节,按照4字节对齐。占4字节。
d按照4字节对齐占4字节。
a+b+c+d占8字节,所以test2占8字节。
2.结果部分
从结果可以看出test1大小为4字节,test2大小为8字节