/* Program to convert a decimal integer to a user-specified base in "C". */ #include /* includes */ #include #define MAXBASE 36 /* constants */ #define MAXBUF 80 void DoConversion (long arg, long base, char *result); /* prototypes */ static char LUT[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; /* globals */ static char result[MAXBUF]; /* Main program */ int main (int argc, char *argv[]) { long arg1, arg2; /* Check for the correct number of arguments. Make sure arguments are in range. */ if (argc != 3) { printf("Usage: BaseConv [value] [Target Base]\n"); return (0); } sscanf(argv[1],"%ld",&arg1); sscanf(argv[2],"%ld",&arg2); if (arg2 < 1 || arg2 > MAXBASE) { printf("Base must be between 1 and %d\n",MAXBASE); return (0); } /* The DoConversion method is used to convert to the target base. It takes 3 arguments: the integer to be converted, the target base, and a pointer to the string to be returned. */ DoConversion(arg1,arg2,result); /* Display result and end. */ printf("%ld in Base %ld is %s\n",arg1,arg2,result); } /* DoConversion is defined exactly as described in class and in the accompanying notes. */ void DoConversion (long arg, long base, char *result) { long Q, Rmdr; char sign; int index; /* Recall that the algorithm computes each digit in the target base from the least significant digit to the most significant digit. The character string "result" is filled in reverse order and reversed on completion. */ Rmdr=0; sign=' '; /* Check for negative */ if (arg < 0) { arg = -arg; sign = '-'; } Q=arg; /* Apply successive division until 0, computing a digit in the target base on each iteration. A lookup table is used to associate a character with the numerical value computed on the current pass. */ index=0; while (Q > 0) { Rmdr = Q % base; Q = Q/base; result[index++] = LUT[Rmdr]; } /* if the sign is "-", append to the mose significant bit (the end of the string). */ if (sign == '-') result[index++] = sign; /* In "C", strings must be terminated bu a NULL. */ result[index++]='\0'; /* Reverse the string. */ strrev(result); }