HomeC ProgrammingC Program to Convert Binary to Decimal

C Program to Convert Binary to Decimal

This C program converts a binary number to its decimal equivalent using the power of 2. It takes a binary number as input and returns the corresponding decimal number.

Problem statement

Write a C program to convert a binary number to its decimal equivalent.

C Program to Convert Binary to Decimal

#include <stdio.h>

int binaryToDecimal(long long binaryNumber);

int main() {
    long long binaryNumber;
    
    printf("Binary to Decimal Converter\n");
    printf("Enter a binary number: ");
    scanf("%lld", &binaryNumber);
    
    int decimalNumber = binaryToDecimal(binaryNumber);
    
    printf("Decimal equivalent: %d\n", decimalNumber);
    
    return 0;
}

int binaryToDecimal(long long binaryNumber) {
    int decimalNumber = 0, i = 0, remainder;
    
    while (binaryNumber != 0) {
        remainder = binaryNumber % 10;
        binaryNumber /= 10;
        decimalNumber += remainder * (1 << i);
        ++i;
    }
    
    return decimalNumber;
}

How it works?

  1. The program prompts the user to enter a binary number.
  2. The binary To Decimal function is called, passing the binary number as an argument.
  3. Inside the binary To Decimal function, the decimal number is initialized to 0, and i (power of 2) is initialized to 0.
  4. The binary number is processed digit by digit in a loop until it becomes 0.
  5. In each iteration, the rightmost digit (remainder) of the binary number is extracted using the modulus operator %.
  6. The binary number is divided by 10 to remove the rightmost digit.
  7. The decimal number is updated by adding remainder * (1 << i) (which is equivalent to remainder * 2^i) to it.
  8. i is incremented by 1 to move to the next power of 2.
  9. The process continues until the binary number becomes 0.
  10. Finally, the decimal number is returned.
  11. The decimal number is printed as the output.

Input/Output

Share:

Leave A Reply

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

You May Also Like

This C program calculates the volume and surface area of a sphere using its radius. A sphere is a three-dimensional...
This C program converts a Roman numeral to a decimal number. Roman numerals are a system of numerical notation used...
This C program calculates the value of sin(x) using the Taylor series expansion. The Taylor series expansion is a mathematical...