Write a C program called convert2base.c that is similar to convert2hex.c, but ha
ID: 3664590 • Letter: W
Question
Write a C program called convert2base.c that is similar to convert2hex.c, but has 2 command line parameters, the first being an integer in the range 2 though 36, and the second being a decimal number. Instead of converting to base 16, the base used is given by the first parameter.
Example
If I wrote the program,
convert2base 23 314156
would generate the following output:
Run your program with each of the following command line parameters and include the output.
23 314156
2 2147483647
31 263429442133726086
36 3881091294471582038
Explanation / Answer
Here is the code for you:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * strrev(char *str)
{
int i = strlen(str)-1,j=0;
char ch;
while(i>j)
{
ch = str[i];
str[i]= str[j];
str[j] = ch;
i--;
j++;
}
return str;
}
int main(int argc, char* argv[])
{
int base = atoi(argv[1]);
long int number = atoi(argv[2]);
char newNumber[100];
int i = 0, rem;
long int numDup;
numDup = number;
while(number != 0)
{
rem = number % base;
number /= base;
if(rem < 10)
newNumber[i++] = (char)(48 + rem);
else
newNumber[i++] = 'A'+rem-10;
}
newNumber[i] = '';
printf("%li base 10 is %s base %i ", numDup, strrev(newNumber), base);
}
If you have any further queries, just get back to me.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.