Answer to Question #310694 in C++ for Ben

Question #310694

3. computeTwos ComplementBinary function :This function takes a static array , bit pattern length, and an integer number as its arguments . The function must populate the array with the two's complement binary representation of the integer number argument in the given bit pattern length. Assume the all the arguments are valid      4. binaryAddition function This function takes two static arrays, bit pattern length, and a third static array as its arguments . The function must populate the third array with the binary sum of the first two arrays in the given bit pattern lengthAssume the first two arrays are populated with binary bits in the given bit pattern length Moreover assume that all the arguments are valid.


1
Expert's answer
2022-03-13T06:03:34-0400
#include <iostream>
using namespace std;
void printBinary(unsigned bits[], unsigned length);


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


void binaryAddition(unsigned op1[], unsigned op2[], unsigned add[], unsigned length) {
    int carry = 0;


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


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], op2[N], sum[N];
    int x;


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


    binaryAddition(op1, op2, sum, N);
    cout << endl;
    printBinary(op1, N);
    printBinary(op2, N);
    printBinary(sum, N);


    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