将十进制转换为 8 位二进制补码 C++

时间:2021-02-23 05:26:49

标签: c++ twos-complement

任务是将十进制值转换为 8 位二进制补码。输入需要介于 -128 和 127 之间。目前,我的程序仅适用于正数。我在编码方面相当新,所以我一直被困住,希望得到任何帮助。

#include <iostream>
#include <string>
using namespace std;

int DecimalToBinary(int dec);

int main() {
    int userInput;

    cout << "Enter a value: ";
    cin >> userInput;

    if (userInput >= -128 && userInput <= 127) {
        int dec = userInput;
        cout << userInput << " = ";
        DecimalToBinary(dec);
    }
    else {
        cout << "Enter a value between -128 and 127: ";
        cin >> userInput;
        if (userInput >= -128 && userInput <= 127)
        {
            int dec = userInput;
            cout << userInput << " = ";
            DecimalToBinary(dec);
        }
    }
    return 0;
}

int DecimalToBinary(int dec)
{
    int bin[1000] = {};     // array to store binary number

    int i = 0;
    while (dec > 0) {       //calculating the binary
        bin[i] = dec % 2;   //storing remainder
        dec = dec / 2;
        ++i;
    }

    // printing binary in 8 bit & reverse order
    int bits = 8;
    if (i > 8) {
        bits = 8 * ((i + 7) / 8);
    }
    for (int j = bits - 1; j >= 0; j--) {
        cout << bin[j];
    }
    return dec;;
}

2 个答案:

答案 0 :(得分:2)

使用字符串流和掩码的解决方案,并附有说明

Two's Complement

<块引用>

在二进制补码表示法中,非负数用其普通的二进制表示法表示;在这种情况下,最高有效位是 0。虽然,表示的数字范围与无符号二进制数不同。例如,一个 8 位无符号数可以表示 0 到 255 (11111111) 之间的值。

<块引用>

然而,一个二进制补码 8 位数字只能表示从 0 到 127 (01111111) 的正整数,因为其余的位组合的最高有效位为 '1' 表示负整数 -1 到 -128。

#include <sstream>
#include <cstring>
#include <iostream>

using namespace std;

string DecimalToBinary(int n) {
    stringstream ss((n < 0) ? "1" : "0"); // the first bit, for any integer, indicates if its negative or not
    if (n < 0)
        n = -(n+1); // read about two complement!
    int mask = 1 << 6; // Since int8_t has only 8 bits you just need to have your mask initialized to 2^6 (equivalent to 0b01000000) as your initial mask that will help you to detect the 7 following bits, from left to right.

    while (mask) {
        ss << ((mask & n) ? "1" : "0"); // if the bit of the mask matches the bit of n then we add it to the string.
        mask >>= 1; // 0b01000000 becomes 0b00100000 and so on
    }
    return ss.str();
}

也改变:

cout << userInput << " = " << DecimalToBinary(dec) << "\n";

或者,您可以使用缓冲区字符数组保留您的方法,但其长度只需要 9 个字符:第一个字符是符号('1' 表示负数,'0' 表示 pos),然后是 7 位生成值,并以 '\0' 结束字符串。

enter image description here

<块引用>

补码运算是加法逆运算,所以负数用绝对值的补码表示。

答案 1 :(得分:0)

#include <bitset>
#include <iostream>
#include <string>

int main() {

int i_val = -128;
char ch = (char)i_val;

std::bitset<8> x(ch);
std::cout << x << '\n';
    // or other way
    std::string s;

    for (int i = sizeof(char) * 8 - 1; i >= 0; i--)
    {
        if ((a >> i) & 1) s += '1';
        else s += '0';
    }
    std::cout << s << "\n";
    return 0;
}
相关问题