您的位置:首页 > 运维架构

An introduction to bitwise operators

2007-12-15 20:52 399 查看
读了codeproject上的这篇《An introduction to bitwise operators》,前面两个运算符说得不错,但第三个异或运算符感觉不够准确,作者给出的示例不知道有什么用处,不就是把数做了两次异或又回来了么?
&运算符用来判定某些位是0还是1:


#include <iostream>


using namespace std;


int main(void)






{


int num = 17;


if(num&0x10)






{


cout<<"第四位是"<<endl;


}


else






{


cout<<"第四位是"<<endl;


}


return 0;


}
|运算符用来对某些位置1:


#include <iostream>


using namespace std;


int main(void)






{


int num = 50;


num = num|0x04;


cout<<hex<<num<<endl;


return 0;


}



异或运算符最常用的应该是用其实现两个数的交换:


#include <iostream>


using namespace std;


int main(void)






{


int n1 = 17,n2 = 20;


n1 = n1^n2;


n2 = n2^n1;


n1 = n1^n2;


cout<<n1<<" "<<n2<<endl;


return 0;


}




将取反运算符和与运算符结合起来,可以对某些位置零:


#include <iostream>


using namespace std;


int main(void)






{


int b = 50;


cout << "b = " << b << endl;


int c = b & ~0x10;


cout <<hex<< "c = " << c << endl;


return 0;


}



最后的位域有一个问题没搞懂:


#include <iostream>


using namespace std;




struct date_struct






{


int day:4, // 1 to 31


month : 4, // 1 to 12


year:12;


};




int main(void)






{


date_struct d1;


d1.day = 8;


d1.month = 8;


d1.year = 1844;


cout<<d1.year<<" "<<d1.month<<" "<<d1.day<<endl;


return 0;


}



我已经设置day和month各自占据4位,应该是可以满足的,可结果却都是-8,why?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: