1.测试代码
#include<stdio.h>
2 struct test
3 {
4 >---unsigned int a:1;
5 >---unsigned int b:2;
6 };
7 int main()
8 {
9 >---struct test st;
10 >---for( st.a=0;st.a<=1;st.a++)
11 >--->---for(st.b=0;st.b<=3;st.b++)
12 >---printf("a=%d>---b=%d\n",st.a,st.b);
13
14 >---return 0;
15 }
这段代码输出的死循环,因为b会溢出然后从3变到0,然后一直循环
2.位域
struct test
3 {
4 >---unsigned int a:1;
5 >---unsigned int b:2;
6 };
如这个结构体,其中a占1个bit,b占两个bit,当用不了一个字节的时候这种运算就有其优点了,当然不能定义unsigned int a:18;
不能超出8位,而且一个位域不能放在两个字节中。
注意int和unsigned int区别就行了,一个有符号另一个无符号
3.位运算
表达式(或声明) | 位模式 |
---|---|
int a=6; | 0···00110 |
int b=11; | 0···01011 |
a&b | 0···00010 |
a|b | 0···01111 |
a^b | 0···01101 |
~a | 1···11001 |