Saturday, June 18, 2016

C Program Code: Convert Binary to Decimal

C Program Code:

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int convertToDecimal(const char binary[]);
int main()
{
    char binaryNumber[17]; // 16 characters for 16-bit Binary  Number and one for ''.
    int decimalNumber;
    printf("Binary to Decimal Converter in C \n");
    printf("Enter 16-bit Binary  Number : ");
    scanf("%s", binaryNumber);
    decimalNumber = convertToDecimal(binaryNumber);
    printf("Decimal Number is %d \n", decimalNumber);
    printf("Press enter to continue... \n");
    fflush(stdin);
    getchar();
    return 0;
}
int convertToDecimal(const char binaryNumber[])
{
    const char *binaryString = binaryNumber;
    int length = 0;
    int decimalNumber = 0;
    int base = 2;        // Base Of Binary Number
    int i;
    // Find length of Binary Number
    for (; *binaryString != '\0'; binaryString++)
    {
        length++;
    }
    // Find Decimal Number
    binaryString = binaryNumber;
    for (i = 0; *binaryString != '\0' && i < length; i++, binaryString++)
    {
        if (*binaryString == '0')
        {
            // Multiplying by zero, equal to zero. So you can discard statement written below.
            decimalNumber += 0 * pow(base, length - i - 1);
        }
        else if (*binaryString == '1')
        {
            decimalNumber += 1 * pow(base, length - i - 1);
        }
        else
        {
            printf("Invalid Binary Number \n");
            printf("Binary Number Contains only 0's or 1's \n");
            printf("Press enter to continue... \n");
            fflush(stdin);
            getchar();
            exit(0);
        }
    }
    return decimalNumber;
}
Convert Binary to Decimal in C Output Screenshot