hi, i am trying to perform a binary conversion when i am stuck at a point where from Decimal i convert it to Binary the results will be in reversed. Is there a way to reverse the result to make it right?
int main ()
{
int n = 0, number = 0;
cout << "Enter a decimal number";
cin >> number >> n;
int a;
if (number > 0)
{
cout << "Binary representation: ";
while (number > 0)
{
a = number % 2;
number = number / 2;
cout << a;
}
cout << endl;
}
return 0;
}
but my results eg: decimal i key in as: 589
results came out as: 1011001001 (its in reverse)
answer should be: 1001001101 instead.
i know by using a counter i could reverse it by recalculate the length of the result but i have no idea on how to do it and where to place it.
The only other way would be to extract the bits from the most significant end, instead of the least significant end like you're doing, but that's not easier.
I think the best way would be to completely redo the way you go about it, finding the left-most digits first and outputting them in order. The following code will do it (although I'm guessing there is a more efficient way to write it):
#include<iostream>
#include<string>
#include<math.h>
usingnamespace std;
int main() //Start of main function
{
//Variables
int number,n=0,a,c;
cout<<"Enter number to be converted to binary: ";
cin>>number;//number to be converted to binary
a=number; //placeholder for number variable
n--;
do
{
n++;
number=number/2; //figure out value for n
}while(number>0);
number=a; //revert number back to original input
do
{
c=pow(2,n); //c=2^n
a=number/c;
n--;
cout<<a;
number%=c;
}while(n>=0);
return 0;
}