第2章 编程问题 2.2节 3
编写一个程序,读取包含一个位运算符的输入行——&、|、^、<<或>>,位运算符的后面跟着整数操作数,接着输出这些整数操作数、位运算符以及将位运算符应用到操作数所得的结果。将这些数字同时以十进制形式和32位的二进制形式显示,使用问题1中的printBinary()函数。例如,输入
& 13 27
将产生输出
Applying the bitwise AND operator & to the following
13 = 0000 0000 0000 0000 0000 0000 0000 1101
27 = 0000 0000 0000 0000 0000 0000 0001 1011
produces
9 = 0000 0000 0000 0000 0000 0000 0000 1001
而输入
~ 1
产生输出
Applying the bitwise NOT operator ~ to the following
1 = 0000 0000 0000 0000 0000 0000 0000 0001
produces
-2 = 1111 1111 1111 1111 1111 1111 1111 1110
注意:实际输出二进制形式时没有空格,这里是为了让各位看清位数
C++实现:
#include <iostream>
using namespace std;
void printBinary(int value);
void bitOperation();
void main() {
bitOperation();
system("pause");
}
void bitOperation() {
char operate_text[][11] = { "NOT", "AND", "OR", "XOR", "LEFTSHIFT", "RIGHTSHIFT" };
int index = 0;//每个操作符所对应的文本描述在数组中的序号(以0开始)
char operate[100] = { 0 };//操作符,申请了一块较长的内存,防止用户的非法输入
int operand1, operand2;//两个操作数
int result = 0;//操作数运算的结果
cin >> operate;
if (strcmp(operate,"~") == 0) {//用strcmp函数判断用户输入的操作符是否合法
cin >> operand1;
index = 0;
result = ~operand1;
}
else {
cin >> operand1 >> operand2;
if (strcmp(operate, "&") == 0) {
index = 1;
result = operand1 & operand2;
}
else if (strcmp(operate, "|") == 0) {
index = 2;
result = operand1 | operand2;
}
else if (strcmp(operate, "^") == 0) {
index = 3;
result = operand1 ^ operand2;
}
else if (strcmp(operate, "<<") == 0) {
index = 4;
result = operand1 << operand2;
}
else if (strcmp(operate, ">>") == 0) {
index = 5;
result = operand1 >> operand2;
}
else {//如果用户输入的操作符不是位运算符,将输出错误提示
cout << "INPUT ERROR!" << endl;
cout << "The operator " << "\"" << operate << "\"" << " is invalid." << endl;
return;
}
}
cout << "Applying the bitwise " << operate_text[index] << " operator " << operate << " to the follwing" << endl;
cout << "\t" << operand1 << " = ";
printBinary(operand1);
cout << endl;
if (index != 0) {
cout << "\t" << operand2 << " = ";
printBinary(operand2);
cout << endl;
}
cout << "produces" << endl;
cout << "\t" << result << " = ";
printBinary(result);
cout << endl;
}
//这是上一篇中使用的函数,这里用来输出操作数和运算结果的二进制形式
void printBinary(int value) {
int bitOfBinary = sizeof(value) * 8;//sieof运算符获取value占几个字节,一个字节是8位
unsigned int mask = 1 << (bitOfBinary - 1);//假设bitOfBinary是32,将1左移31位得到10000000000000000000000000000000
for (int i = 1; i <= bitOfBinary; i++) {
int temp = mask & value;
if (temp == 0) {
cout << 0;
}
else {
cout << 1;
}
mask >>= 1;//每次将mask右移一位
}
}