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

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


本文转自Phinecos(洞庭散人)博客园博客,原文链接:http://www.cnblogs.com/phinecos/archive/2007/12/15/996211.html,如需转载请自行联系原作者
目录
相关文章
UVa11296 - Counting Solutions to an Integral Equation(枚举技巧)
UVa11296 - Counting Solutions to an Integral Equation(枚举技巧)
47 0
|
Python
Python编程:Built-in Functions内建函数小结
Python编程:Built-in Functions内建函数小结
172 0
|
SQL 移动开发 算法
New Dynamic Programming Algorithm for the Generation of Optimal Bushy Join Trees
MySQL无疑是现在开源关系型数据库系统的霸主,在DBEngine的最新排名中仍然稳居第2位,与第3位SQL Server的积分差距并不算小,可以说是最受欢迎,使用度最高的数据库系统,这一点看看有多少新型数据库要兼容MySQL的协议和语法就知道了。
307 0
New Dynamic Programming Algorithm for the Generation of Optimal Bushy Join Trees
|
安全 iOS开发 编译器
Effective Objective-C 2.0
本书是iOS开发进阶的必读书籍之一。文中部分名词的中文翻译略坑,比如对block和GCD的翻译。其他整体还好,原作者写的比较用心。代码规范讲了不少,底层原理讲了一点点,且主要集中在第二章。
1386 0
1088. Rational Arithmetic (20)
For two rational numbers, your task is to implement the basic arithmetics, that is, to calculate their sum, difference, product and quotient.
788 0