&:按位与
|:按位或
^:按位异或
~:按位取反
1.......&//对应的二进制位相与,有0则为0,两个同时为1才为1.
#include<stdio.h>
int main()
{
int a = -5;
int b = 13;
int c = a&b;
// 10000000000000000000000000000101
//111111111111111111111111111111111010
//111111111111111111111111111111111011 -5的补码
//00000000000000000 000000000001101 13的补码
//00000000000000000000000000001001 9
printf("%d\n",c);
return 0;
}
2.......|//对应的二进制位相与,有1则为1,两个同时为0才为0.
int main()
{
int a = -5;
int b = 13;
int c = a|b;
// 1000000000000000000000000101
//11111111111111111111111111111010
//111111111111111111111111 11111011 -5的补码
//00000000000000000000000000001101 13的补码
//11111111111111111111111111111111 补码
//1000000000000000000000000001 原码---->-1
printf("%d\n",c);
return 0;
}
3......^ 相同为0,相异为1
int main()
{
int a = -5;
int b = 13;
int c = a^b;
// 10000000000000000000000000000101
//111111111111111111111111111111111010
//111111111111111111111111111111111011 -5的补码
//00000000000000000000000000001101 13的补码
//111111111111111111111111111111110110
//10000000000000000000000000001001 取反加1
//10000000000000000000000000001010 -10
printf("%d\n",c);
return 0;
}
4......~按位取反
有1变0,有0变1
他们的操作数必须是整数
int main()
{
int a = 0;
//00000000000000000000000000000000
//11111111111111111111111111111111
//10000000000000000000000000000000
//10000000000000000000000000000001
//printf("%d\n",~a);//~a就是对a进行按位取反
//rerurn 0;
}
练习:不能创建第三个变量,实现两个整数的变换
int main()
{
int a = 10;
int b = 20;
printf("交换前:a=%d b=%d\n",a,b);
//可能存在溢出问题
a = a+b;
b=a-b;
a=a-b;
printf("交换后:a=%d b=%d",a,b);
return 0;
}
处理后:
int main()
{
int a = 10;
int b = 20;
printf("交换前:a=%d b=%d\n",a,b);
a = a^b;
b=a^b;
a=a^b;
printf("交换后:a=%d b=%d",a,b);
return 0;
}
-1存在内存中是32个1.。。。。补码
练习:求一个整数储存在内存中的二进制中1的个数
//针对负数是有问题的
int main()//(磨2除2)
{
int n = 13;
int count = 0;
while(n)
{
if(n% 2== 1)
count++;
n = n/2;
}
printf("%d\n",count);
return 0;
}
修改
int main()
{
int n = 13;
int count = 0;
while(n)
{
if(n% 2== 1)
count++;
n = n/2;
}
printf("%d\n",count);
return 0;
}