This snippet has a will convert Decimal number to Binary number.
Convert Decimal to Binary
// coverts decimal to binary
// vishesh
// 21/05/2005
#include <iostream>
char* DEC_BIN(int);
int main()
{
//
int num;
std::cout << "Enter a number: ";
std::cin >> num;
std::cout << DEC_BIN(num);
std::cin.get();
return 0;
}
char* DEC_BIN(int dec)
{
using namespace std;
char *rtn;
int prev, len, temp, *bin;
prev = dec;
for(int i=0;prev!=0;i++)
{
prev = prev/2;
len=i;
}
bin = new int[len+1];
prev = dec;
for(int i=0;prev!=0;i++)
{
bin[i] = prev%2;
prev = prev/2;
len=i;
}
bin[len+1] = prev%2;
len++;
for(int i=0;i<len/2;i++)
{
temp=bin[i];
bin[i]=bin[len-1-i];
bin[len-1-i]=temp;
}
rtn = new char[len+1];
for(int i=0;i<len;i++)
{
rtn[i]=bin[i]+'0';
rtn[i+1]='\0';
}
return rtn;
}
hashjoe 0 Newbie Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.