1 位运算介绍

#include <iostream>
#include <string>
using namespace std;

int main()
{
int a=12;//a= 00000000 00000000 00000000 00001100
int b=6; //b= 00000000 00000000 00000000 00000110

//按位与运算 输出4
cout<<(a&b)<<endl;

//按位或运算 输出14
cout<<(a|b)<<endl;

//取反 输出-13 a= 00000000 00000000 00000000 00001100 ~a=11111111 11111111 11111111 11110011
//补码 其值为 -00000000 00000000 0000000 00001101=-13
cout<<(~a)<<endl;

//右移 a= 00000000 00000000 00000000 00000110
cout<<(a>>1)<<endl;

float c=1.0;
//cout<<(a&c)<<endl; 浮点数不能和整数进行位运算
//cout<<(c>>1)<<endl;浮点数同样不能进行移位

//字符支持移位运算 str=01100001 tar=0110010
char str='a';
char tar='b';
cout<<(str>>1)<<endl;

//字符支持位运算
cout<<(str&tar)<<endl;

return 0;
}



输出结果:

经典算法之位运算_#include


2 位算法

经典算法之位运算_ios_02

经典算法之位运算_ios_03


算法四的代码:

#include <iostream>
#include <string>
using namespace std;

//判断一个数转换为二进制后的1的位数
int num(int value)
{
int temp=value;
int k;
int i=0;
while(temp>0)
{
k=temp;
temp=temp>>1;
if(k-2*temp!=0)
{
i++;
}
}
return i;
}
int main()
{
cout<<num(10)<<endl;

return 0;
}