# Converting a decimal number to its binary, octal and hexadecimal equivalent

 Tweet

This is a C program which demonstrates how to convert a decimal number to its binary, octal and hexadecimal equivalent.

You can compile this program on bOtskOOl Free Online C/C++ Compiler.

//A C PROGRAM TO CONVERT DECIMAL TO BINARY,OCTAL,HEXADECIMAL

/*
**********************
www.botskool.com
**********************
*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i,num,*bin,*oct,bin_len,oct_len,hex_len;
char *hex,ch;
clrscr();
do
{
printf("\n Enter the number to be converted :");
scanf("%d",&num);
//printf("\n%c\n",(char)48);
printf("\n");
//binary
bin_len=binary(bin,num);
printf("\nBinary : ");
for(i=0;i<bin_len;i++)
printf("%d",bin[i]);
printf("\n");

//octal
oct_len=octal(oct,num);
printf("\nOctal : ");
for(i=0;i<oct_len;i++)
printf("%d",oct[i]);
printf("\n");

for(i=0;i<hex_len;i++)
printf("%c",hex[i]);
printf("\n");

printf("\nEnter another number(y/n)?");
ch=getche();
getch();
}while(ch!='n');

}

int binary(int *bin,int num)
{
int rem=0,i=0;

do{
rem=num%2;
num=num/2;
bin[i]=rem;
i++;
}while(num>0);

array_reverse_i(bin,i);
return i;
}
int octal(int *oct,int num)
{
int rem=0,i=0;

do{
rem=num%8;
num=num/8;
oct[i]=rem;
i++;
}while(num>0);

array_reverse_i(oct,i);
return i;
}
{
int rem=0,i=0;

do{
rem=num%16;
num=num/16;

switch (rem)
{
case 10 : hex[i]='A';
i++;
break;
case 11 : hex[i]='B';
i++;
break;
case 12 : hex[i]='C';
i++;
break;
case 13 : hex[i]='D';
i++;
break;
case 14 : hex[i]='E';
i++;
break;
case 15 : hex[i]='F';
i++;
break;

default :hex[i]=(char)(rem+48);
i++;
}

}while(num>0);

array_reverse_c(hex,i);
return i;
}

array_reverse_i(int *arr,int len)
{
int i,temp;
for(i=0;i<len/2;i++)
{
temp=arr[i];
arr[i]=arr[len-1-i];
arr[len-1-i]=temp;

}
return 0;
}
array_reverse_c(char *arr,int len)
{
int i;
char temp;
for(i=0;i<len/2;i++)
{
temp=arr[i];
arr[i]=arr[len-1-i];
arr[len-1-i]=temp;

}
return 0;
}
/*
**********************
www.botskool.com
**********************
*/

Output will be like this:-

Terms of Agreement:
By using this code, you agree to the following terms-
1) You may use this code in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
2) You MAY NOT redistribute this code (for example to a web site) without written permission from us. Failure to do so is a violation of copyright laws.
3) You may link to this code from another website, but ONLY if it is not wrapped in a frame.
4) You will abide by any additional copyright restrictions which may have placed in the code or code's description.
>>Kindly post your doubts and suggestions on our discussion forum.
 Tweet
Tags: