In C programming:
Generalize the to_binary() function of Listing 9.8 (from your textbook) to a to_base_n(number,base) function that takes a second argument in the range 2–10. It then should convert (and print) the number that is its first argument to the number base given by the second argument. For example, tobasen(129,8) would display 201, the base-8 equivalent of 129. Test the function in a complete program.
#include <stdio.h>
#include <string.h>
char reVal(int num)
{
if (num >= 0 && num <= 9)
return (char)(num + '0');
else
return (char)(num - 10 + 'A');
}
void strev(char *str)
{
int len = strlen(str);
int i;
for (i = 0; i < len / 2; i++)
{
char temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
}
char *to_base_n(char res[], int base, int inputNum)
{
int index = 0;
while (inputNum > 0)
{
res[index++] = reVal(inputNum % base);
inputNum /= base;
}
res[index] = '\0';
strev(res);
return res;
}
int main()
{
int inputNum, base;
printf("Enter input number: ");
scanf("%d",&inputNum);
printf("Enter base: ");
scanf("%d",&base);
char res[100];
printf("Equivalent of %d in base %d is %s\n",inputNum, base, to_base_n(res, base, inputNum));
return 0;
}
//SAMPLE OUTPUT:
PLEASE LIKE IT RAISE YOUR THUMBS UP
IF YOU ARE HAVING ANY DOUBT FEEL FREE TO ASK IN COMMENT
SECTION
Get Answers For Free
Most questions answered within 1 hours.