源文件:
#include <stdio.h>
#include <stdarg.h>
int main()
{
struct bs{
int a:5;
int b:5;
int c:5;
int d:5;
int e:5;
int f:5;
int g:2;
char h:5;
}__attribute__((packed)) data; //定义位域结构体变量data (取消了字节对齐)
int i;
long long * x;
long long temp;
int length;
data.a = 3;
data.b = 5;
data.c = 5;
data.d = 7;
data.e = 7;
data.e = 7;
data.f = 21;
data.g = 0;
data.h = 21; //初始化data的每一个位域
x=(long long *) &data;
temp=1;
length = sizeof(data) * 8;
char bits[sizeof(data)*8 + 1 ]; //存储data的每一位
for(i = 0; i < length ; i++ ) {
if(*x & ( temp << i ) )
bits[length - i -1] = '1';
else
bits[length - i -1] = '0';
}
bits[sizeof(data)*8] = '\0';
printf("\n");
printf("bits of data is %ld\n",sizeof(data)*8);
printf("data : %s\n",bits); //打印data的每一位
return 0;
}
运行结果:
bits of data is 40
data : 0001010100101010011100111001010010100011