位域

注意空域。unsigned默认是4个字节。

 1 #include <iostream>
 2 
 3 using namespace std;
 4 struct B1{
 5     unsigned a:4;
 6     unsigned b:4;
 7 };
 8 
 9 struct B2{
10     unsigned a:4;
11     unsigned :0;
12     unsigned b:4;
13 };
14 
15 struct B3{
16     unsigned char a:4;
17     unsigned char b:4;
18 };
19 
20 struct B4{
21     unsigned char a:4;
22     unsigned :0;
23     unsigned char b:4;
24 };
25 
26 struct B5{
27     unsigned char a:4;
28     unsigned char b:4;
29     unsigned :0;
30 };
31 
32 struct B6{
33     unsigned char a:4;
34     unsigned char b:5;
35 };
36 int main(int argc, char** argv) {
37     cout << "sizeof(B1): " << sizeof(B1) << endl;
38     cout << "sizeof(B2): " << sizeof(B2) << endl;
39     cout << "sizeof(B3): " << sizeof(B3) << endl;
40     cout << "sizeof(B4): " << sizeof(B4) << endl;
41     cout << "sizeof(B5): " << sizeof(B5) << endl;
42     cout << "sizeof(B6): " << sizeof(B6) << endl;
43     return 0;
44 }

输出:

1 root@xxj-VirtualBox:~/interview# ./bitfield 
2 sizeof(B1): 4
3 sizeof(B2): 8
4 sizeof(B3): 1
5 sizeof(B4): 5
6 sizeof(B5): 4
7 sizeof(B6): 2

 

posted @ 2014-10-01 16:49  linyx  阅读(176)  评论(0编辑  收藏  举报