#include #include #define SIZE 100 #define LIMIT 32 double num2dec ( char *num, unsigned int base ) { unsigned int point, pos, whole, boost; double frac; // find the point position for ( point=0; (num[point]!='.' && num[point] != '\0'); ++point ) ; // calculate the decimal equivalent of the whole part for ( pos=point, boost=1, whole=0; pos>0; --pos ) { if ( (num[pos-1] >= '0') && (num[pos-1] <= '9') ) whole += (num[pos-1]-'0') * boost; if ( (num[pos-1] >= 'A') && (num[pos-1] <= 'Z') ) whole += (num[pos-1]-'A'+10) * boost; boost *= base; } // calculate the decimal equivalent of the fractional part if ( num[point] != '\0' ) { for ( pos=point, boost=base, frac=0; num[pos+1] != '\0'; ++pos ) { if ( (num[pos+1] >= '0') && (num[pos+1] <= '9') ) frac += (double) (num[pos+1]-'0') / boost; if ( (num[pos+1] >= 'A') && (num[pos+1] <= 'Z') ) frac += (double) (num[pos+1]-'A'+10) / boost; boost *= base; } } return whole+frac; } char *dec2new ( double dec, unsigned int new ) { unsigned int whole = dec, itr = 0; double frac = dec - whole; char num[SIZE] = "", part[SIZE] = "", digit[SIZE]; // calculate equivalent number in new base of the whole part while ( whole > 0 ) { sprintf(digit, "%u", whole%new); strcat(digit, num); strcpy(num, digit); whole /= new; } // calculate equivalent number in new base of the fractional part while ( frac > 0 ) { // breaking for potential non-terminating sequences if ( ++itr > LIMIT ) break; frac = frac * new; if ( frac >= 10 ) digit[0] = (int)frac + 'A' - 10; else digit[0] = (int)frac + '0'; digit[1] = '\0'; strcat(part, digit); frac -= (int)frac; } // determine whether the output is not a whole number and put point in between if ( part[0] != '\0' ) strcat(num, "."); return strcat(num, part); } int main () { char num[SIZE]; unsigned int base, new; double dec; // take a number as a string printf("Enter Number: "); scanf("%s", num); // take the base of the number printf("Enter Base (<= 36): "); scanf("%u", &base); // output the number in decimal (base 10) dec = num2dec(num,base); printf("Number in Base 10 (Decimal) = %.32lg\n", dec); // take a new base as input printf("Enter New Base (<= 36): "); scanf("%u", &new); // output the number in new base printf("Number in Base %u = %s\n", new, dec2new(dec,new)); return 0; }