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

来源:互联网 发布:茶叶网络推广 编辑:程序博客网 时间:2024/04/30 14:57


头文件

/*** 功能:输出移位运算符的操作* 时间: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;}




0 0
原创粉丝点击