# Decimal to Binary conversion using C Programming

CServer Side ProgrammingProgramming

## Problem

How to convert a decimal number to a binary number by using the function in the C programming language?

## Solution

In this program, we are calling a function to binary in main(). The called function to binary will perform actual conversion.

The logic we are using is called function to convert decimal number to binary number is as follows −

while(dno != 0){
rem = dno % 2;
bno = bno + rem * f;
f = f * 10;
dno = dno / 2;
}

Finally, it returns the binary number to the main program.

## Example

Following is the C program to convert a decimal number to a binary number −

Live Demo

#include<stdio.h>
long tobinary(int);
int main(){
long bno;
int dno;
printf(" Enter any decimal number : ");
scanf("%d",&dno);
bno = tobinary(dno);
printf("\n The Binary value is : %ld\n\n",bno);
return 0;
}
long tobinary(int dno){
long bno=0,rem,f=1;
while(dno != 0){
rem = dno % 2;
bno = bno + rem * f;
f = f * 10;
dno = dno / 2;
}
return bno;;
}

## Output

When the above program is executed, it produces the following result −

Enter any decimal number: 12
The Binary value is: 1100

Now, try to convert binary numbers to decimal numbers.

## Example

Following is the C program to convert binary number to decimal number −

Live Demo

#include
#include <stdio.h>
int todecimal(long bno);
int main(){
long bno;
int dno;
printf("Enter a binary number: ");
scanf("%ld", &bno);
dno=todecimal(bno);
printf("The decimal value is:%d\n",dno);
return 0;
}
int todecimal(long bno){
int dno = 0, i = 0, rem;
while (bno != 0) {
rem = bno % 10;
bno /= 10;
dno += rem * pow(2, i);
++i;
}
return dno;
}

## Output

When the above program is executed, it produces the following result −

Enter a binary number: 10011
The decimal value is:19