I just noticed (or rather, figured out why it was happening) a problem with the code as above, so here is a fixed version:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
#define BUFSIZE 1024
/* function prototypes */
long string2long(char* rep, unsigned int base);
void Binary2Decimal();
void Octal2Decimal();
void Hexa2Decimal();
char buffer[BUFSIZE];
long string2long(char* rep, unsigned int base)
{
unsigned int len, i, digit;
long sub_result, result = 0;
len = strlen(rep); /* get the length of the string */
for (i = 0; i < len; i++)
{
/* take the ASCII value of the digit
and subtract it by the ASCII value of '0' */
digit = rep[i] - '0';
sub_result = digit * (long) pow(base, len - (i + 1));
result += sub_result; /* add sub_result to the rolling total */
}
return result;
}
void Binary2Decimal()
{
long result;
printf("[BINARY TO DECIMAL CONVERSION]\n");
printf("Enter a Binary number: ");
fgets(buffer, BUFSIZE, stdin);
buffer[strlen(buffer) - 1] = '\0'; /* eliminate the trailing newline */
result = string2long(buffer, 2);
printf("\n\n");
printf("Decimal equivalent is: %d\n", result);
}
void Octal2Decimal()
{
long result;
printf("[OCTAL TO DECIMAL CONVERSION]\n");
printf("Enter an Octal number: ");
fgets(buffer, BUFSIZE, stdin);
buffer[strlen(buffer) - 1] = '\0';
printf("\n\n");
result = string2long(buffer, 8);
printf("Decimal equivalent is: %d\n", result);
}
void Hexa2Decimal()
{
long result;
printf("[HEXADECIMAL TO DECIMAL CONVERSION]\n");
printf("Enter a Hexadecimal number: ");
fgets(buffer, BUFSIZE, stdin);
buffer[strlen(buffer) - 1] = '\0';
printf("\n\n");
result = string2long(buffer, 2);
printf("Decimal equivalent is: %d\n", result);
}
int main()
{ …