C Language Practice: Binary to Decimal

From Eric & Company
Jump to navigation Jump to search

Binary to Decimal

This is my first practice. I got a bit confused with the code when I first met the problem, but in the end I got it.

‎

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

int btod(char *binary)
{
    int i;
    int decimal = 0;
    int place = 0, temp = 0;

    for(i = strlen(binary) - 1; i >= 0; --i)
    {
        if ((binary[i] == '0') || (binary[i] == '1'))
        {
            temp = binary[i] - '0';
        }
        else
        {
            printf("error: not a valid binary number\n");
            exit(0);
        }

        decimal += temp * pow(2, place);
        place++;
    }

    printf("the decimal number of this binary number is: %d\n", decimal);

    return decimal;
}

int main(void)
{
    char binary[10];
    scanf("%s", binary);

    btod(binary);

    return 0;
}


‎