How to convert decimal number to binary number using functions in C language?
In this program, we call a binary function in main(). The binary number conversion function called will perform the actual conversion.
The logic of the calling function we use to convert decimal numbers to binary numbers is as follows -
while(dno != 0){ rem = dno % 2; bno = bno + rem * f; f = f * 10; dno = dno / 2; }
Finally, the binary number is returned to the main program.
The following is a C program to convert a decimal number to a binary number-
< p> Live demonstration#include<stdio.h> long tobinary(int); int main(){ long bno; int dno; printf(" Enter any decimal number : "); scanf("%d",&dno); bno = tobinary(dno); printf("</p><p> The Binary value is : %ld</p><p></p><p>",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;; }
When executed 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 the binary number to decimal number.
The following is a C program to convert a binary number to a decimal number -
Live Demonstration
#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</p><p>",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; }
When executed When executing the above program, the following results will be produced -
Enter a binary number: 10011 The decimal value is:19
The above is the detailed content of Implementation of C language program for converting decimal to binary. For more information, please follow other related articles on the PHP Chinese website!