6、C++基础:位运算
2016-11-17 本文已影响8人
blueskylxb
有一个unsigned long型整数,先要分别将其前2个字节和后2个字节用为两个unsigned int型整数输出(设一个int型数据占2个字节),试编写一函数partition实现上述要求。要求在主函数输入该long型整数,在函数partition中输出结果
#include <iostream>
#include <cmath>
using namespace std;
void partition(unsigned long in){
unsigned int outL;
unsigned int outR;
unsigned int right = pow(2, 16) - 1; // 值为65535
outL = in >> 16; // 右移运算符>>,即向右移16位,移到右端的低位被舍弃,高位补0
outR = in & right; // 与二进制数按位与运算,right为65535,即 00000000 00000000 11111111 11111111
cout << "左边两字节数:" << outL << endl;
cout << "右边两字节数:" << outR << endl;
}
int main(void){
unsigned long in;
cout << "long字节数:" << sizeof(long) << endl;
cout << "输入无符号长整形值:" << endl;
cin >> in;
partition(in);
return 0;
}