Home > Backend Development > C++ > Implementation of C language program for converting decimal to binary

Implementation of C language program for converting decimal to binary

WBOY
Release: 2023-09-06 23:09:05
forward
1453 people have browsed it

Implementation of C language program for converting decimal to binary

Question

How to convert decimal number to binary number using functions in C language?

Solution

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;
}
Copy after login

Finally, the binary number is returned to the main program.

Example

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;;
}
Copy after login

Output

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

Enter any decimal number: 12
The Binary value is: 1100
Copy after login

Now, try to convert the binary number to decimal number.

Example

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;
}
Copy after login

Output

When executed When executing the above program, the following results will be produced -

Enter a binary number: 10011
The decimal value is:19
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template