An introduction to bitwise operators

读了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;
}

我已经设置daymonth各自占据4位,应该是可以满足的,可结果却都是-8why?

posted on   Phinecos(洞庭散人)  阅读(368)  评论(0编辑  收藏  举报

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述

导航

点击右上角即可分享
微信分享提示