Answer to Question #310698 in C++ for Lil Top

Question #310698

5. twos ComplementBinaryToDecimal function This function takes a static array and bit pattern length as its arguments. The function must return the decimal (integer) value computed from the two's complement binary representation given in the array argument in the given bit pattern length. Assume the array is populated with binary bits in the given pattern length and that it is a two's complement representation .


1
Expert's answer
2022-03-13T06:04:00-0400
#include <iostream>
using namespace std;


void computeUnsignedBinary(unsigned bits[], unsigned length, unsigned x) {
    for (unsigned i=0; i<length; i++) {
        bits[length-1-i] = (x % 2 == 1) ? 1 : 0;
        x /= 2;
    }
}


void computeTwosComplementaryBinary(unsigned bits[], unsigned length, int x) {
    unsigned ux = x >=0 ? x : -x;


    computeUnsignedBinary(bits, length, ux);
    if (x>=0) {
        return;
    }


    for (unsigned i=0; i<length; i++) {
        bits[i] ^= 1;
    }


    int carry = 1;
    for (int i=length-1; i>=0; i--) {
        int res = bits[i] + carry;
        bits[i] = res % 2;
        carry = res / 2;
    }
}


int twosComplementBinaryToDecimal(unsigned bits[], unsigned length) {
    bool neg = bits[0] == 1;


    if (neg) {
        for (unsigned i=0; i<length; i++) {
            bits[i] ^= 1;
        } 


        int carry = 1;
        for (int i=length-1; i>=0; i--) {
            int res = bits[i] + carry;
            bits[i] = res % 2;
            carry = res / 2;
        }   
    }


    int x = 0;
    for (unsigned i=1; i<length; i++) {
        x <<= 1;
        x += bits[i];
    }
    if (neg) {
        x = -x;
    }
    return x;
}


void printBinary(unsigned bits[], unsigned length) {
    for (unsigned i=0; i<length; i++) {
        cout << bits[i];
    }
    cout << endl;
}

int main() {
    const unsigned N=8;
    unsigned op1[N];
    int x;

    cout << "Enter an integer: ";
    cin >> x;
    computeTwosComplementaryBinary(op1, N, x);
    printBinary(op1, N);

    x = twosComplementBinaryToDecimal(op1, N);
    cout << x;

    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment