写出下列各整数的原码、反码、补码表示(用8位二进制数)。
(1)-35 (2)127 (3)-127 (4) -1
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
system("chcp 65001");
freopen("C:/Users/zhaochen/Desktop/input.txt", "r", stdin);
cin.tie(0);
cout.tie(0);
int n, question = 0;
while (cin >> n) {
printf("\n(%d)\n", ++question);
bitset<7> b(abs(n));
if (n > 0) {
cout << n << "的原码: " << 0 << b << endl;
cout << n << "的反码: " << 0 << b << endl;
cout << n << "的补码: " << 0 << b << endl;
} else {
cout << n << "的原码: " << 1 << b << endl;
b = ~b;
cout << n << "的反码: " << 1 << b << endl;
b = bitset<7>(b.to_ulong() + 1);
cout << n << "的补码: " << 1 << b << endl;
}
}
return 0;
}
模拟:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
string fanMa(string str) {
if (str[0] == '1') {
for (int i = 1; i < str.length(); i++) {
if (str[i] == '0') {
str[i] = '1';
} else {
str[i] = '0';
}
}
}
return str;
}
string buMa(string fan) {
if (fan[0] == '1') {
int flag = 1; // 标记要进位1
for (int i = fan.length() - 1; i >= 0; i--) {
if (fan[i] == '0') {
if (flag) {
flag = 0;
fan[i] = '1';
}
} else if (fan[i] == '1') {
if (flag) {
fan[i] = '0';
}
}
}
}
return fan;
}
int main() {
system("chcp 65001");
freopen("C:/Users/zhaochen/Desktop/input.txt", "r", stdin);
cin.tie(0);
cout.tie(0);
int n, question = 0;
while (cin >> n) {
printf("\n(%d)\n", ++question);
bitset<7> b(abs(n));
string str = "0";
if (n < 0) {
str = "1";
}
str += b.to_string();
cout << n << "的原码: " << str << endl;
string fan = fanMa(str);
cout << n << "的反码: " << fan << endl;
string bu = buMa(fan);
cout << n << "的补码: " << bu << endl;
}
return 0;
}