How do I Reverse Binary Number?

+1 Hasib Ullah · November 9, 2015
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?

my code is as follows:


#include <iostream>

using namespace std;

int main()
{
    int number = 0;

   cout << "Enter a decimal number:";
   cin >> number ;

int a;

if (number > 0)
{
   cout << "Binary representation: ";

   while (number > 0)
   {
      a = number % 2;
      number = number / 2;
     cout << a;
   }
}
}

Post a Reply

Replies

Oldest  Newest  Rating
0 Stevan Zečević · November 9, 2015
well first you write loop to see how long array you need something like this 

int i = 0;
while(number != 0){
number = number /2;
i = i+1;
}

then you create array length = i and every time you do a = number % 2 put a in array
int i = 0;
while (number > 0){
array(i)= a;//cant show array brackets dont' know why so i used regular 
a = number % 2;
number = number / 2;
cout << a; 
i = i +1;
}

code looks something like this maybe i skipped line or two 
0 Hasib Ullah · November 9, 2015
How to do that?
0 Stevan Zečević · November 9, 2015
you could store binary representation in array and print it backwards
  • 1

C++

107,164 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator