结构体中的位字段

z指定的位数决定了结构体变量d的大小,当z:29时,占用4个字节,共32位;当z:32时,需要使用8个字节,占用35位,自动补齐。一个int型占用4个字节。


#include <iostream>  
#include <stdio.h>  
  
using namespace std;  
  
struct a {  
    int x:1;  
    int y:2;  
    int z:29;  
};  
  
int main()  
{  
    a d;  
	d.x=1;
	d.y=2;
	d.z=9;
    printf("%d \n", d);
    printf("%d \n", sizeof(d));
    while(1);
    return 0;  
}  


输出结果:77      4

其中77对应的二进制数为:1001101   对应十进制的:9(1001)2(10)1(1)


#include <iostream>  
#include <stdio.h>  
  
using namespace std;  
  
struct a {  
    int x:1;  
    int y:2;  
    int z:32;  
};  
  
int main()  
{  
    a d;  
	d.x=1;
	d.y=2;
	d.z=9;
    printf("%d \n", d);
    printf("%d \n", sizeof(d));
    while(1);
    return 0;  
}  

输出结果:-858993459      8

猜你喜欢

转载自blog.csdn.net/qqyuanhao163/article/details/52229321