
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Decimal to Binary Conversion Using C Programming
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 −
#include<stdio.h> long tobinary(int); int main(){ long bno; int dno; printf(" Enter any decimal number : "); scanf("%d",&dno); bno = tobinary(dno); printf("
The Binary value is : %ld
",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 −
#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
",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
Advertisements