Convert Decimal to Binary

GreenDay2001 0 Tallied Votes 147 Views Share

This snippet has a will convert Decimal number to Binary number.

// 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

na na na lot of work :
works in C pretty well :

#include<stdio.h>
main() 
{
    int i=0,q,num,r[20];
    printf("\n\n\nEnter Number\n\n\n");
    scanf("%d",&num);
    q = num/2;
    r[0] = num%2;
    while (q>1)
     {
        q = q/2;
        r[i+1] = q%2;
        printf("\n\n\n\nbinary is %s\n\n\n",r);
        ++i;
     }
    getch();
}
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.