简体   繁体   中英

Decimal to Binary in C++

I'm a total beginner in C++ and today I thought I'd write myself a small program that converts a decimal number to binary. The code looked something like this:

#include <iostream>
void binaryConvert(int);
int main() {
    using namespace std;
    cout << "Enter decimal number for conversion:" << endl;
    int dec;
    cin >> dec;
    binaryConvert(dec);
}
void binaryConvert(int number) {
    using namespace std;
    while(number > 0) {
        int bin = number % 2;
        number /= 2;
        cout << bin;
    }
}

Logically, this program would print the binary the other way around. I spent a long time trying to figure out how to invert the order of the binary digits so that the binary number would appear the right way around when I came across this piece of code:

void binaryConvert(int number) {
    using namespace std;
    if(number > 0) {
        int bin = number % 2;
        number /= 2;
        binaryConvert(number);
        cout << bin;
    }
}

I know its probably a stupid question (I'm an absolute beginner), but I can't figure out why this code prints the bits in the correct order. Also, how come the bits actually get printed if the function gets called again before cout even gets executed?

Basically because "cout" is called after "binaryConvert". It's like putting all the bits in a stack and after that printing them.

It utilizes recursion, the bin at the end will not be printed until the base case is hit (number <= 0) and then it will go up the stack trace.

This function is a recursive one. It is calling itself recursively to print the least significant digits first, before printing out the most significant ones.

int num;
string BinaryRepresentation="";
cout<<"Input:";
cin>>num;
string  newstring= "";

bool h;
h = true;

while(h){
    BinaryRepresentation += boost::lexical_cast<std::string>( num % 2 );
    num = num / 2;
    if ( num < 1){
        h = false;
    }
}
for ( int i = BinaryRepresentation.size() - 1; i >= 0; i--){
    newstring += BinaryRepresentation[i];

}
     cout<< "Binary Representation: " << newstring <<endl;

}

Mainly the idea of the program is to find the reminder of the number and divide the number by 2 and and keep on repeating the same procedure until the number becomes 0. The you need to reverse the string in order to get the binary equivalent of the entered number.

As you have correctly mentioned your program inverted the binary as it gave the output. To put the binary in the correct order to The second code starts giving output only once the final bit is obtained. The order of output is bin to the bin and hence we obtain the desired output. The following code may help your understanding further: http://ideone.com/Qm0m7L

void binaryConvert(int number) {
    if(number > 0) {
        int bin = number % 2;
        number /= 2;
        cout << bin<<" one"<<endl;
        binaryConvert(number);
        cout << bin<<" two"<<endl;
    }
}

The output obtained is:

0 one
0 one
0 one
1 one
1 two
0 two
0 two
0 two

The output that precedes " one" is what your program would have given. I hope you understand the difference.

While I was searching online to convert from decimal to binary, didn't find a simple and an understandable solution. So I wrote a program on my own. Here it goes.

 #include <iostream>
#include <string>
#include <sstream>

using namespace std;
void dtobin(int n)
{
   ostringstream oss;
   string st="";
if(n<0)
{
    cout<<"Number is negative";
    return;
}
   int r;
while(n!=1)
{

    r=n%2;
    oss<<st<<r;
    n/=2;
}
oss<<st<<1;
st=oss.str();
cout<<st;
//To reverse the string
int len=st.length();
int j=len-1;
char x;
for(int i=0;i<=len/2-1;i++)
{
    x=st[i];
    st[i]=st[j];
    st[j]=x;
    --j;
}
cout<<endl<<st;
}


  int main()
{
  int n;
  cout<<"ENTER THE NUMBER";
  cin>>n;
  dtobin(n);
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM