按位运算
运算符 | 含义 |
---|---|
& | 按位的与 |
| | 按位的或 |
~ | 按位的取反 |
^ | 按位的异或(两个位相等为0,不相等为1) |
<< | 按位的左移 |
.>> | 按位的右移(有符号数,保留符号,即最高位不变) |
例1:数据的二进制类型输出
#include <stdio.h>
int main(int argc,char const *argv[])
{
int num = 12345;
unsigned mask = 1u<<31;
for ( ; mask ; mask >>=1 ){
printf("%d",num & mask?1:0);
}
printf("\n");
return 0;
}
例2:位段操作
#include <stdio.h>
void printBin(unsigned int num);
typedef struct{
unsigned int lead : 3;
unsigned int flag1: 1;
unsigned int flag2: 1;
int trailing: 27;
//int一共32位
}UN;
int main(int argc,char const *argv[])
{
UN uu;
uu.lead = 7;
uu.flag1 = 1;
uu.flag2 = 1;
uu.trailing = 0;
printf("sizeof(uu)=%lu\n",sizeof(uu));
printBin(*(int*)&uu); //强行转化为int类型指针
return 0;
}
void printBin(unsigned int num){
unsigned mask = 1u<<31;
for ( ; mask ; mask >>=1 ){
printf("%d",num & mask?1:0);
}
printf("\n");
}
lead、flag1、flag2占5位