1、
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char** argv) { union { struct { unsigned char a:1; unsigned char b:2; unsigned char c:3; }d; unsigned char e; } f; f.e = 1; printf("%d\n",f.d.a); return 0; }
(小端情况下)输出:1
为什么要加上小端情况下这个限制呢?我是这样想的,正确性有待证明,一个字节有8比特位,从左到右暂且称之为
b7 b6 b5 b4 b3 b2 b1 b0, 那么unsigned char a:1;到底对应哪一位呢,是b7还是b0。如果是小端的话就是b0,如果是大端的话,就是b7。
这个知识点还有待继续深挖,下面两个网址里的内容以后要研究一下
http://blog.163.com/niuxiangshan@126/blog/static/1705965952011529103742195/
http://en.wikipedia.org/wiki/Endianess
2、
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char** argv) { union { struct { char a:1; char b:2; char c:3; }d; char e; } f; f.e = 1; printf("%d\n",f.d.a); return 0; }
(小端情况下)输出:-1
3、unsigned 与signed
struct test { short a : 2; unsigned short b : 3; }; //输出 2,not 4
4、地址不可取
最后说的一点就是位域是一个字节单元里面的一段,是没有地址的!
5、
While we're on the subject of structures, we might as well look at bitfields. They can only be declared inside a structure or a union (or a class in c++), and allow you to specify some very small objects of a given number of bits in length. Their usefulness is limited and they aren't seen in many programs, but we'll deal with them anyway.
6、
#include <stdio.h> int main(void) { struct { /* field 4 bits wide */ unsigned field1 :4; /* * unnamed 3 bit field * unnamed fields allow for padding */ unsigned :3; /* * one-bit field * can only be 0 or -1 in two's complement! */ signed field2 :1; /* align next field on a storage unit */ unsigned :0; unsigned field3 :6; }full_of_fields; printf("%d\n", sizeof(full_of_fields)); return 0; } 输出8
7、
#include <stdio.h> int main(void) { struct { /* field 4 bits wide */ unsigned field1 :4; /* * unnamed 3 bit field * unnamed fields allow for padding */ unsigned :3; /* * one-bit field * can only be 0 or -1 in two's complement! */ signed field2 :1; unsigned field3 :6; }full_of_fields; printf("%d\n", sizeof(full_of_fields)); return 0; }
//输出4