Here is a very simple and recursively written C++ program to convert a decimal integer number into its binary equivalent. However it returns the binary equivalent in the form of a string of characters but you can very easily write an other function to convert this string into an actual binary number as well.
#include <iostream>
#include <string>
using namespace std;
//takes an integer as an argument and
//returns its binary equivalent in the
//form of a string of characters
string dec_to_binary(int);
////////////.............\\\
int main()
{
int number;
cout << "Enter a decimal number to convert it into a binary number:n";
cin >> number;
cout << dec_to_binary(number) << endl;
system("pause");
return 0;
}
string dec_to_binary(int num)
{
if (num==0)
return "0";
else if (num==1)
return "1";
else if (num<0)
return "-"+(dec_to_binary(-num));
else
return (dec_to_binary(num/2)+static_cast<char>((num%2)+48));
}
If you want me to explain any part of this program or have suggestions to improve it then please tell me via comments. I will try my best to respond promptly.
