Aziz Ahmed
Aziz Ahmed

Reputation: 49

Is this program for binary to decimal is correct?

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


int main() {
    long long int bin;
    int dec=0,i;

    scanf("%lld", &bin);
    for(i=0; bin!=0; i++){
        if(bin%10==0 || bin%10==1){
            dec+=(bin%10)*pow(2,i);
            bin/=10;
        }
        else {
            printf("Invalid Binary number!!\n");
            return 0;
        }

    }
    printf("%d\n", dec);


    return 0;
}

I make this program to convert binary to decimal. There are many code in online but I want to know Is everything ok with this code?

Upvotes: 1

Views: 87

Answers (2)

zwol
zwol

Reputation: 140748

It would be better to read character by character and convert directly to a machine number. That more clearly expresses your intent.

#include <stdio.h>
#include <limits.h>

int main(void)
{
    unsigned long long n = 0;
    int c;
    fputs("enter a number in base 2: ", stdout);
    while ((c = getchar()) != EOF && c != '\n') {
        if (n >= (ULLONG_MAX >> 1) + 1) {
            fprintf(stderr, "binary number is too large\n");
            return 1;
        }
        n <<= 1;
        if (c == '0')
            n += 0;
        else if (c == '1')
            n += 1;
        else {
            fprintf(stderr, "bad binary digit '%c'\n", c);
            return 1;
        }
    }
    printf("that number in base 10 is %llu\n", n);
    return 0;
}

Completely untested. Negative numbers left as an exercise (caution: shifting into the sign bit of a signed integer provokes undefined behavior).

Upvotes: 1

Govind Parmar
Govind Parmar

Reputation: 21562

Your code does have some issues:

  1. You should always check for scanf failing. On success, scanf returns the number of items in the argument list successfully filled, so if the return value is something other than 1 (in your case) you should print an error and stop there.
  2. You don't need to use pow at all. Multiplying an integer by a power of 2 is the same as shifting it left, but faster since you aren't calling a function that returns a double. Replace *pow(2, i) with << i and you get the same result.
  3. From a usability perspective, you should print out messages to the screen.

This is much better:

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


int main() 
{
    long long int bin;
    int dec=0,i;
    printf("Enter a number in base 2: ");
    if(scanf("%lld", &bin)!=1)
    {
        printf("Error reading your input.");
        return -1;
    }
    for(i=0; bin!=0; i++)
    {
        if(bin%10==0 || bin%10==1)
        {
            dec+=(bin%10) << i;
            bin/=10;
        }
        else
        {
            printf("Invalid Binary number!!\n");
            return 0;
        }

    }
    printf("That number in base 10 is: %d\n", dec);


    return 0;
}

Upvotes: 0

Related Questions