user2086751
user2086751

Reputation:

decimal to binary converter c++?

int inputNumber=0;
int divisionStore=0,modStore=0;
vector<int> mainVector;

cout << "\nEnter a Number to Convert to Binary.\n" << endl;

cin >> inputNumber;

do
{
    modStore=inputNumber%2;
    inputNumber=inputNumber/2;
    mainVector.push_back(modStore);

}while(inputNumber!=1);

for (int i=0;i<mainVector.size();i++)
{
    cout<<endl<<mainVector[i]<<endl;
}

Seems like there is a logical error but I cant find whats wrong with it? The program does not print the correct conversion as it seems like the loop ends before it can push the last number.

Upvotes: 1

Views: 6927

Answers (6)

Bilal Tahir
Bilal Tahir

Reputation: 45

  #include<iostream>
    using namespace std;
    int main(){
    int x,bin;
    x=0 ,bin=0;
           int ar[10000];
           cout<<"Enter Decimal Number "<<endl;
            cin>>x;
        int n=0;
            while(x>0){
                bin=x%2;
                x=x/2;
                ar[n]=bin;
                n++;
                }

cout<<endl;
n=n-1;

    for(n;n>=0;n--){
cout<<ar[n]; }
cout<<endl;

return 0;
}
/* Try this */

Upvotes: 0

Karoly Horvath
Karoly Horvath

Reputation: 96326

inputNumber%2 is the least significant bit, so your vector will contain the bits in reversed order. Simply loop the vector in reversed order.

while(inputNumber!=1) - You have to loop while inputNumber!=0, otherwise you won't process the last bit.

Upvotes: 0

pakupo
pakupo

Reputation: 151

I answered similar question Here, I used recursion function

void decimal_to_binary(int decimal)
{
    int remainder = decimal % 2;
    if (decimal < 1)
        return;
    decimal_to_binary(decimal / 2);
    cout << remainder;
}

Upvotes: 0

Bishop
Bishop

Reputation: 188

Seams to be a very complicated and inefficient way (if I don't misunderstand you). You are probably looking for bit-manipulation operators, not /, % etc. If you really want to stick it in a vector this should do it:

while (inputNumber) {
  mainVector.push_back(inputNumber & 1);
  inputNumber >>= 1;
}

Note however that this will put the least significant bit at the beginning of the vector, may not be what you want but looks like it is what your code is trying to do as well.

Upvotes: 0

Ed Heal
Ed Heal

Reputation: 60037

Why not use the STL - i.e. bitset

See http://www.cplusplus.com/reference/bitset/bitset/to_string/

Probably do it in a couple lines of code!

Upvotes: 2

Paul R
Paul R

Reputation: 213200

I think you need to change:

}while(inputNumber!=1)

to:

}while(inputNumber!=0)

Upvotes: 4

Related Questions