Binary to Decimal Conversion in C
Binary to Decimal Conversion
Binary to Decimal conversion is the process of converting a binary number (base-2) into its equivalent decimal number (base-10). Each binary digit represents a power of 2.
For example, the binary number 1010 is equal to decimal 10 because:
(1 × 2³) + (0 × 2²) + (1 × 2¹) + (0 × 2⁰) = 8 + 0 + 2 + 0 = 10
We will explore three methods to convert a binary number to a decimal number using C programming.
Method 1: Using Loop
#include <stdio.h> #include <math.h> int binaryToDecimal(long long n) { int decimal = 0, i = 0; while (n != 0) { int lastDigit = n % 10; decimal += lastDigit * pow(2, i); n /= 10; i++; } return decimal; }
Output:
Enter a binary number: 1010 Decimal equivalent (Loop): 10
Method 2: Using Recursion
#include <stdio.h> #include <math.h> int binaryToDecimalRecursive(long long n, int i) { if (n == 0) return 0; return (n % 10) * pow(2, i) + binaryToDecimalRecursive(n / 10, i + 1); }
Output:
Enter a binary number: 1010 Decimal equivalent (Recursion): 10
Method 3: Using Bitwise Operations
#include <stdio.h> int binaryToDecimalBitwise(int n) { int decimal = 0, base = 1; while (n > 0) { int lastDigit = n % 10; decimal += lastDigit * base; base *= 2; n /= 10; } return decimal; }
Output:
Enter a binary number: 1010 Decimal equivalent (Bitwise): 10
Main Function
#include <stdio.h> int main() { long long binary; printf("Enter a binary number: "); scanf("%lld", &binary); printf("Decimal equivalent (Loop): %d\n", binaryToDecimal(binary)); printf("Decimal equivalent (Recursion): %d\n", binaryToDecimalRecursive(binary, 0)); printf("Decimal equivalent (Bitwise): %d\n", binaryToDecimalBitwise(binary)); return 0; }