Cover Image for Binary to Decimal Number in C
96 views

Binary to Decimal Number in C

To convert a binary number to a decimal number in C, you can follow a simple algorithm that involves iterating through the binary digits from right to left and multiplying each digit by the appropriate power of 2. Here’s a C program to perform this conversion:

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

int binaryToDecimal(long long binaryNumber) {
    int decimalNumber = 0, i = 0, remainder;

    while (binaryNumber != 0) {
        remainder = binaryNumber % 10;
        binaryNumber /= 10;
        decimalNumber += remainder * pow(2, i);
        ++i;
    }

    return decimalNumber;
}

int main() {
    long long binaryNumber;

    printf("Enter a binary number: ");
    scanf("%lld", &binaryNumber);

    int decimalNumber = binaryToDecimal(binaryNumber);

    printf("Decimal equivalent: %d\n", decimalNumber);

    return 0;
}

In this program:

  1. We define a function binaryToDecimal that takes a long long integer representing a binary number as input and returns its decimal equivalent.
  2. Inside the binaryToDecimal function, we initialize decimalNumber to 0 to store the result and i to 0 to keep track of the position of each binary digit.
  3. We use a while loop to iterate through the binary digits. In each iteration, we extract the rightmost digit (remainder) using the modulo operator (%) and divide the binary number by 10 to remove the rightmost digit.
  4. We calculate the decimal value of the extracted digit by multiplying it by 2 raised to the power of i and add it to decimalNumber.
  5. We increment i to move to the next position in the binary number.
  6. Finally, we return the decimalNumber.

In the main function, we take input from the user as a binary number, call the binaryToDecimal function to perform the conversion, and then display the decimal equivalent.

Compile and run the program, and it will convert a binary number to its decimal representation.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS