Q:

C Program For Convert Binary Number to Decimal or Decimal Number to Binary Using Function

0

The Binary Number is number which has base 2. which consists of only two numerical symbols ‘1’ and ‘0’ and each digit is referred to as a ‘Bit’.

 

What is Decimal Number?

The number which has base 10 is called a Decimal Number system.

For Example 0101=2^3*0+2^2*1+2^1*0+2^0*1=0+4+0+1=5.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#include <stdio.h>
#include <math.h>
int bin_to_dec(int n);
int dec_to_bin(int n);
int main()
{
   int n;
   char c;
   printf("Instructions:\n");
   printf("1. Enter alphabet 'd' to convert binary to decimal.\n");
   printf("2. Enter alphabet 'b' to convert decimal to binary.\n");
   scanf("%c",&c);
   if (c =='d' || c == 'D')
   {
       printf("Enter a binary number: ");
       scanf("%d", &n);
       printf("%d in binary = %d in decimal", n, bin_to_dec(n));
   }
   if (c =='b' || c == 'B')
   {
       printf("Enter a decimal number: ");
       scanf("%d", &n);
       printf("%d in decimal = %d in binary", n, dec_to_bin(n));
   }
   return 0;
}

int dec_to_bin(int n)  /* Function to convert decimal to binary.*/
{
    int rem, i=1, binary=0;
    while (n!=0)
    {
        rem=n%2;
        n/=2;
        binary+=rem*i;
        i*=10;
    }
    return binary;
}

int bin_to_dec(int n) /* Function to convert binary to decimal.*/

{
    int decimal=0, i=0, rem;
    while (n!=0)
    {
        rem = n%10;
        n/=10;
        decimal += rem*pow(2,i);
        ++i;
    }
    return decimal;
}

 

Output:

Instructions:

1. Enter alphabet 'd' to convert binary to decimal.

2. Enter alphabet 'b' to convert decimal to binary.

d

Enter a binary number: 110101001

110101001 in binary = 425 in decimal

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now