Categories
c programming Programs

C Program to Convert Binary Number to Decimal

// convert binary to decimal

#include <stdio.h>
#include <math.h>

// function prototype
int convert(long long);

int main() {
  long long n;
  printf("Enter a binary number: ");
  scanf("%lld", &n);
  printf("%lld in binary = %d in decimal", n, convert(n));
  return 0;
}

// function definition
int convert(long long n) {
  int dec = 0, i = 0, rem;

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

  return dec;
}

Output

Enter a binary number: 1101
1101 in binary = 13 in decimal

In the program, we have included the header file math.h to perform mathematical operations in the program.

We ask the user to enter a binary number and pass it to the convert() function to convert it decimal.

Suppose n = 1101. Let’s see how the while loop in the convert() function works.

n != 0rem = n % 10n /= 10idec += rem * pow(2, i)
1101 != 01101 % 10 = 11101 / 10 = 11000 + 1 * pow (2, 0) = 1
110 != 0110 % 10 = 0110 / 10 = 1111 + 0 * pow (2, 1) = 1
10 != 011 % 10 = 111 /10 = 121 + 1 * pow (2, 2) = 5
1 != 01 % 10 = 11 / 10 = 035 + 1 * pow (2, 3) = 13
0 != 0Loop terminates

So, 1101 in binary is 13 in decimal.

Now, let’s see how we can change the decimal number into a binary number.

Example 2: C Program to convert decimal number to binary

// convert decimal to binary

#include <stdio.h>
#include <math.h>

long long convert(int);

int main() {
  int n, bin;
  printf("Enter a decimal number: ");
  scanf("%d", &n);
  bin = convert(n);
  printf("%d in decimal =  %lld in binary", n, bin);
  return 0;
}

long long convert(int n) {
  long long bin = 0;
  int rem, i = 1;

  while (n!=0) {
    rem = n % 2;
    n /= 2;
    bin += rem * i;
    i *= 10;
  }

  return bin;
}

Output

Enter a decimal number: 13
13 in decimal = 1101 in binary

Suppose n = 13. Let’s see how the while loop in the convert() function works.

n != 0rem = n % 2n /= 2ibin += rem * ii * = 10
13 != 013 % 2 = 113 / 2 = 610 + 1 * 1 = 11 * 10 = 10
6 != 06 % 2 = 06 / 2 = 3101 + 0 * 10 = 110 * 10 = 100
3 != 03 % 2 = 13 / 2 = 11001 + 1 * 100 = 101100 * 10 = 1000
1 != 01 % 2 = 11 / 2 = 01000101 + 1 * 1000 = 11011000 * 10 = 10000
0 != 0Loop terminates

Thus, 13 in decimal is 1101 in binary.

Leave a Reply

Your email address will not be published. Required fields are marked *