首页 > 解决方案 > 寻找二进制补码,

问题描述

这是要计算的代码:任何人,在帮助将有符号整数转换为其二进制等效值(8 位)(在 2 的补码中),反之亦然。程序应该能够 t0 首先读取用户提供的有符号整数或二进制数(始终为 2 的补码)

例如,当我输入00110101转换为有符号十进制时,我会得到203. 但正确答案是53

#include <iostream>
#include <string>

using namespace std;

string decimalToBinary(int);
string findTwosComplement(string);

string decimalToBinary(int n) {
    if (n < 0)
        n = 256 + n;
    string res = "";
    while (n > 0)
    {
        res = string(1, (char)(n % 2 + 48)) + res;
        n = n / 2;
    }
    return res;
}

string decimalToBinary(int n) {
    if (n < 0)
        n = 256 + n;
    string res = "";
    while (n > 0)
    {
        res = string(1, (char)(n % 2 + 48)) + res;
        n = n / 2;
    }
    return res;
}

string findTwosComplement(string s)
{
        int num = s.length();

    int i;
    for (i = num - 1; i >= 0; i--)
        if (s[i] == '1')
            break;
    if (i == -1)
        return '1' + s;
    for (int j = i - 1; j >= 0; j--)
    {
        if (s[j] == '1')
            s[j] = '0';
        else
            s[j] = '1';
    }
    return s;
}

标签: c++

解决方案


我假设你想要这个用于教学目的,否则你只是这样做(signed char) n

这两个补码-2<<(n-1) + sum(2<<k for 0 <= k < n-1)对于 8 位来说是数字的通常二进制表示,0 <= N < 128不同之处在于最高有效位不是加 128,而是减 128。这就是它可以表示数字的原因-128 <= N < 128。重要的是,您可以通过复制信号位来增加数字的宽度。C++ 数字已经是 2 补码 32 位数字,因此对于有效范围内的数字,24 个最高有效位要么全为“0”,要么全为“1”,因此您可以将这些位切片。

#include <iostream>
#include <string>

using namespace std;

string decimalToBinary(int n) {
    // C++ integers are already in 2-complements so you only have to 
    // extract the bits.
    if((n < -128) || (n >= 128)){
      std::cerr << "The number "<< n << " does not fit into a 8-bit 2-complement representation" << std::endl;
    }
    string res = "";
    for(int i = 0; i < 8; ++i){
      res = string(1, (char)(((n >> i) & 1) + '0')) + res;
    }
    return res;
}

int binaryToDecimal(string s) {
  // The most significant bit is the signal
  int result = -((int)(s[0] - '0'));

  for(int i = 1; i < s.size(); ++i){
    result = 2*result + ((int)(s[i] - '0'));
  }
  return result;
}

int main(){
  int input;
  while(cin){
    cout << "> ";
    cin >> input;
    string binary = decimalToBinary(input);
    int output = binaryToDecimal(binary);
    cout << input << " -> " << binary << " -> " << output << endl;
  }
}

推荐阅读