0

I'm doing some C++ array homework. The goals is to convert decimal to binary (include negative numbers). Here's my code, it gets the job done, but I would like to see if anything can be improved, or any better algorithm (using binary shift maybe?).

#include <iostream> 
using namespace std;
// doi tu thap phan sang nhi phan
void decToBinary(int n, int nhiphan[])
{
    for (int i=0; i < 16; i++)
    {
        // to binary
        nhiphan[i] = n % 2;
        n = n / 2;
    }
    // inverse array
    for (int i = 0, j = 15; i < j; i++, j--)
    {
        int temp = nhiphan[i];
        nhiphan[i] = nhiphan[j];
        nhiphan[j] = temp;
    }
}
void reverse(int& a)
{
    if (a == 0)
        a++;
    else a--;
}

void outArr(const int a[], int size) {
    for (int i = 0; i < size; ++i)
        cout << a[i];
}

int main()
{
    int nhiphan[16];
    int n;
    do {
        cout << "Nhap so (-255 <= n <= 255) chuyen doi sang nhi phan (16 bit): ";
        cin >> n;
    } while (n > 255 || n < -255);
    if (n < 0) {//check negative
        n *= -1;
        decToBinary(n, nhiphan);
        for (int i = 0; i < 16; i++)// 1's complement
            reverse(nhiphan[i]);
        // +1
        if (nhiphan[15] == 0)//2's complement
            nhiphan[15] = 1;
        else 
        { 
            nhiphan[15] = 0; 
            int i = 15;
            do {
                reverse(nhiphan[i-1]);
                i--;
            } while (nhiphan[i-1] == 0);
        }
    }
    else decToBinary(n, nhiphan);
    outArr(nhiphan, 16);
    return 0;
}
10
  • 1
    This can certainly be improved. The binary representation can be created in the right order in the first place; instead of in the wrong order and then reversed by the second loop. Then, reverse() can be a single statement instead of a confusing if statement. Finally, the shown code assumes sizeof(int) to be 2. This is not necessary true. So, at least three obvious improvements here. Commented Nov 23, 2019 at 16:29
  • You can use std::bitset. Commented Nov 23, 2019 at 16:55
  • @nada They need to write out the algorithm on their own. Commented Nov 23, 2019 at 16:59
  • @0x499602D2 That'd be plausible but not explicitly stated in the question. Commented Nov 23, 2019 at 17:01
  • @nada It's highly plausible given the use of the word "homework". Commented Nov 23, 2019 at 17:03

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.