Base Conversion
Completed
Read a non-negative integer and a base 2–16, and print the number in that base (digits 0-9 then A-F).
Input
n, then lines number base.
Output
One line per conversion.
Example
Input
4 255 16 10 2 0 8 100 7
Output
FF 1010 0 202
Editor
C
Hints
Repeatedly take x % base for the next digit (right to left), then print them reversed.
Solution explanation
The same divide-and-remainder method works for any base.
Show solution
#include <stdio.h>
int main() {
char digits[17];
char out[40];
int n, x, base;
for (int i = 0; i < 16; i++) digits[i] = i < 10 ? '0' + i : 'A' + i - 10;
scanf("%d", &n);
for (int t = 0; t < n; t++) {
scanf("%d %d", &x, &base);
int len = 0;
do {
out[len] = digits[x % base];
len++;
x /= base;
} while (x > 0);
for (int i = len - 1; i >= 0; i--) printf("%c", out[i]);
printf("\n");
}
return 0;
}