Unleashing the Power of C Programming: Converting Between Binary and Decimal

The Art of Conversion

Understanding how to convert between different number systems is crucial when working with numbers. In this article, we’ll explore the world of C programming and learn how to write programs that can seamlessly convert binary numbers to decimal and vice versa.

Cracking the Code: Binary to Decimal

Let’s start with a simple C program that takes a binary number as input and converts it to decimal. To achieve this, we’ll create a user-defined function called convert(). This function will utilize the math.h header file to perform mathematical operations.


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

int convert(char binary[]) {
    int decimal = 0, base = 1;
    int len = strlen(binary);

    for (int i = len - 1; i >= 0; i--) {
        if (binary[i] == '1')
            decimal += base;
        base *= 2;
    }

    return decimal;
}

int main() {
    char binary[10];
    printf("Enter a binary number: ");
    scanf("%s", binary);

    int decimal = convert(binary);
    printf("The decimal equivalent is: %d\n", decimal);

    return 0;
}

The convert() function works as follows:

  • The while loop iterates through each digit of the binary number, starting from the rightmost digit.
  • With each iteration, the loop calculates the decimal equivalent of the binary number.
  • Finally, the function returns the decimal equivalent.

The Reverse Engineer: Decimal to Binary

Now, let’s flip the script and explore how to convert a decimal number to binary. We’ll use a similar approach, creating a user-defined function called convert() (yes, the same name!). This function will also utilize the math.h header file.


#include <stdio.h>

void convert(int decimal) {
    int binary[10];
    int i = 0;

    while (decimal > 0) {
        binary[i++] = decimal % 2;
        decimal /= 2;
    }

    for (int j = i - 1; j >= 0; j--) {
        printf("%d", binary[j]);
    }
}

int main() {
    int decimal;
    printf("Enter a decimal number: ");
    scanf("%d", &decimal);

    printf("The binary equivalent is: ");
    convert(decimal);
    printf("\n");

    return 0;
}

The convert() function works as follows:

  • The while loop iterates through each digit of the decimal number, starting from the rightmost digit.
  • With each iteration, the loop calculates the binary equivalent of the decimal number.
  • Finally, the function returns the binary equivalent.

By mastering these simple yet powerful programs, you’ll gain a deeper understanding of C programming and be able to tackle more complex projects with confidence. So, get coding and unlock the secrets of binary and decimal conversions!

Leave a Reply