简体   繁体   中英

Converting decimal to an 8 bit Twos Complement C++

The assignment is to convert a decimal value to an 8-bit twos complement binary. The input needs to range between -128 & 127. Currently, my program only works for positive numbers. I am fairly new at coding so I've been stuck, and would appreciate any help.

#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;;
}

Solution using stringstream and mask with explanations

Two's Complement

In two's complement notation, a non-negative number is represented by its ordinary binary representation; in this case, the most significant bit is 0. Though, the range of numbers represented is not the same as with unsigned binary numbers. For example, an 8-bit unsigned number can represent the values 0 to 255 (11111111).

However a two's complement 8-bit number can only represent positive integers from 0 to 127 (01111111), because the rest of the bit combinations with the most significant bit as '1' represent the negative integers −1 to −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();
}

Also change:

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

Alternatively, you can keep your approach with a buffer char array, but you only need 9 characters for its length: first char is the sign ('1' for negative and '0' for pos), then the 7 bits that makes the value, and the '\0' ending the string.

在此处输入图像描述

The two's complement operation is the additive inverse operation, so negative numbers are represented by the two's complement of the absolute value.

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM