您的位置:首页 > 编程语言 > C语言/C++

【ThinkingInC++】13、输出移位运算符的操作

2014-08-12 19:59 302 查看

头文件

/**
* 功能:输出移位运算符的操作
* 时间:2014年8月12日20:01:32
* 作者:cutter_point
*/
#ifndef PRINTBINARY_H_INCLUDED
#define PRINTBINARY_H_INCLUDED

#include<iostream>

using namespace std;

void printBinary(const unsigned char val)
{
    for(int i=7 ; i != -1 ; --i)
    {
        if(val & (1<<i))    //位运算符,与
            cout<<"1";  //吧1左移i位,如果和val是匹配的那么就输出1,否则就是0
        else        //一共是8位一个字节
            cout<<"0";
    }
}

#endif // PRINTBINARY_H_INCLUDED


CPP文件

/**
* 功能:输出移位运算符的操作
* 时间:2014年8月12日20:01:43
* 作者:cutter_point
*/

#include"printBinary.h"
#include<iostream>
#include<stdlib.h>

using namespace std;

#define PR(STR, EXPR) cout<<STR; printBinary(EXPR); cout<<endl;

int main()
{
    unsigned int getval;
    unsigned char a, b;
    cout<<"输入一个在0到255之间的数:";    //由于char是一个字节长度8位所以是0到255
    cin>>getval; a=getval;
    PR("a in binary:", a);
    cout<<"输入一个在0到255之间的数:";
    cin>>getval; b=getval;
    PR("b in binary:", b);

    cout<<"----------------------------------------------------------------------------"<<endl;
    PR("a & b:", a&b);
    PR("a | b:", a|b);
    PR("a ^ b:", a^b);
    PR("~a", ~a);
    PR("~b", ~b);

    cout<<"----------------------------------------------------------------------------"<<endl;
    unsigned char c=0x5A;
    PR("c in binary:", c);
    a&=c;
    PR("a&=c; a=", a);
    a|=c;
    PR("a|=c; a=", a);
    a^=c;
    PR("a^=c; a=", a);
    a&=b;
    PR("a&=b; a=", a);
    a|=b;
    PR("a|=b; a=", a);
    a^=b;
    PR("a^=b; a=", a);
    b&=c;
    PR("b&=c; b=", b);
    b|=c;
    PR("b|=c; b=", b);
    b^=c;
    PR("b^=c; b=", b);

    system("pause");
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: