Answer to Question #285955 in C for Codealpha

Question #285955

Write a C Program which converts Binary Number to Decimal and vice-versa. Your program must contain two functions. You have to ask the choice for the user if he/she enter 1 you have to work with BinToDec function if the choice is 2 you have to work with DecToBin function. Both functions take the number in int main part and you have to print the answer in int main part.




1
Expert's answer
2022-01-09T02:20:51-0500
#include <stdio.h>
#include <stdbool.h>
#define BUF_SIZE 80


bool BinToDec(char bin[], char dec[]) {
    long unsigned x = 0;
    char buf[BUF_SIZE];
    int i=0, n=0;


    while (bin[i]) {
        if (bin[i] != '0' && bin[i] != '1') {
            return false;
        }
        x *= 2;
        x += bin[i] - '0';
        i++; 
    }


    if (x == 0) {
        dec[0] = 0;
        dec[1] = '\0';
        return true;
    }


    while (x) {
        buf[n] = (x%10) + '0';
        x /= 10;
        n++;
    }


    for (i=0; i<n; i++) {
        dec[n-i-1] =  buf[i];
    }
    dec[n] = '\0';
    return true;
}


bool DecToBin(char dec[], char bin[]) {
    long unsigned x = 0;
    char buf[BUF_SIZE];
    int i=0, n=0;


    while (dec[i]) {
        if (dec[i] < '0' || dec[i] > '9') {
            return false;
        }
        x *= 10;
        x += dec[i] - '0';
        i++; 
    }


    if (x == 0) {
        bin[0] = 0;
        bin[1] = '\0';
        return true;
    }


    while (x) {
        buf[n] = (x%2) + '0';
        x /= 2;
        n++;
    }


    for (i=0; i<n; i++) {
        bin[n-i-1] =  buf[i];
    }
    bin[n] = '\0';
    return true;
}


int main() {
    char src[BUF_SIZE], dst[BUF_SIZE];
    int choice;

    printf("1 Binary Number to Decimal\n");
    printf("2 Decimal Number to Binary\n");
    printf("Make your choice: ");
    scanf("%d", &choice);
    if (choice != 1 && choice != 2) {
        printf("Incorrect choice\n");
        return 0;
    }

    printf("\nEnter a number: ");
    scanf("%s", src);

    if (choice == 1) {
        if (!BinToDec(src, dst)) {
            printf("Incorrect number input\n");
            return 0;
        }
        printf("%s binary is %s decimal\n", src, dst);
    }
    else {
        if (!DecToBin(src, dst)) {
            printf("Incorrect number input\n");
            return 0;
        }
        printf("%s decimal is %s binary\n", src, dst);      
    }

    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS