C Programming Assignment Help

C Programming Task on Integer Decimal to Base-q Conversion

#include <stdio.h>
#include <string.h>

// To return value for a character. 10 is returned for ‘A’
int val(char c)
{
if (c >= ‘0’ && c <= ‘9’)
return (int)c – ‘0’;
else
return (int)c – ‘A’ + 10;
}

// Function to convert a number from given base ‘q’ to decimal
int q2num(char num_q[], int q)
{
int len = strlen(num_q);
int power = 1; // Initialize power of base
int num = 0; // Initialize result
int i;

// Decimal equivalent is str[len-1]*1 +
// str[len-2]*base + str[len-3]*(base^2) + …
for (i = len – 1; i >= 0; i–)
{
// A digit in input number must be
// less than number’s base
if (val(num_q[i]) >= q)
{
printf(“Invalid Number”);
return -1;
}

num += val(num_q[i]) * power;
power = power * q;
}

return num;
}
// Driver program
int main()
{
int base = 16;
char temp[3]=”11A”;
printf(“%d”,q2num(temp,base));

return 0;
}