Write a C program to convert binary to decimal using recursion.
#include <stdio.h>
#include <string.h>
#include <math.h>
/* convert binary to decimal using recursion */
void binaryToDecimal(char *binary, int *decimal, int *len) {
static int num, i = 0;
if (*len > 0) {
/* parsing string from last character to start */
*len = *len - 1;
num = *(binary + *len) - '0';
*decimal = *decimal + (num * pow(2, i++));
binaryToDecimal(binary, decimal, len);
}
return;
}
int main() {
char binary[256];
int decimal = 0, len;
/* get the input value from the user */
printf("Enter your binary input:");
fgets(binary, 256, stdin);
binary[strlen(binary) - 1]= '\0';
/* find the length of the given binary input */
len = strlen(binary);
/*
* converts binary to decimal and it
* stores the result in decimal
*/
binaryToDecimal(binary, &decimal, &len);
/* prints the resultant decimal value */
printf("Decimal Value: %d\n", decimal);
return 0;
}
Note:
gcc binToDeci.c -lm => linked math library since we have used math function pow().
#include <string.h>
#include <math.h>
/* convert binary to decimal using recursion */
void binaryToDecimal(char *binary, int *decimal, int *len) {
static int num, i = 0;
if (*len > 0) {
/* parsing string from last character to start */
*len = *len - 1;
num = *(binary + *len) - '0';
*decimal = *decimal + (num * pow(2, i++));
binaryToDecimal(binary, decimal, len);
}
return;
}
int main() {
char binary[256];
int decimal = 0, len;
/* get the input value from the user */
printf("Enter your binary input:");
fgets(binary, 256, stdin);
binary[strlen(binary) - 1]= '\0';
/* find the length of the given binary input */
len = strlen(binary);
/*
* converts binary to decimal and it
* stores the result in decimal
*/
binaryToDecimal(binary, &decimal, &len);
/* prints the resultant decimal value */
printf("Decimal Value: %d\n", decimal);
return 0;
}
Note:
gcc binToDeci.c -lm => linked math library since we have used math function pow().
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your binary input:1111111111111111
Decimal Value: 65535
Enter your binary input:1111111111111111
Decimal Value: 65535
No comments:
Post a Comment