原码反码补码计算

写出下列各整数的原码、反码、补码表示(用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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值