结构体中的位字段

来源:互联网 发布:阿里云大数据开发平台 编辑:程序博客网 时间:2024/05/17 22:19

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

0 0