Seems strange to pass base and call the function ...hex...().
Easier to use unsigned rather than int.
if (!number) block not needed if a do {} while (number); loop used.
char buffer[base]; is the wrong sized buffer. Need is more like "log(INT_MAX, base) + 1".
to make this code more efficient,
speed: Code is calling putchar() repetitively. The amount of processing there can well exceed all OP's code. Reducing I/O calls should be then the goal. E.g. Call fputs() once.
// a fast version
int print_fast(unsigned number, unsigned base) {
char buf[sizeof number * CHAR_BIT + 1];
char *end = &buf[sizeof buf] - 1;
*end = '\0';
do {
end--;
*end = "0123456789abcdef"[number % base];
number /= base;
} while (number);
fputs(end, stdout);
return (int) (&buf[sizeof buf] - end - 1);
}
with fewer lines,
See Code Golf for such. Note that reducing lines often goes against efficiently.
// A terse recursive solution
int print_terse(unsigned number, unsigned base) {
int count = 1;
if (number >= base) {
count += print_short(number / base, base);
}
putchar("0123456789abcdef"[number % base]);
return count;
}
without using other standard functions.
Not possible. Some library I/O function needed.
How about a full featured signed one?
Note the buffer needs to be 34 for a 32 bit int.
#include <assert.h>
#include <limits.h>
#include <stdio.h>
int print_int(int number, int base) {
assert(base >= 2 && base <= 36);
char buf[sizeof number * CHAR_BIT + 2];
char *end = &buf[sizeof buf] - 1;
*end = '\0';
// Form the negative absolute value
// Negatives used to cope with `INT_MIN`
int n = (number > 0) ? -number : number;
do {
end--;
*end = "0123456789abcdefghijklmnopqrstuvwxyz"[-(n % base)];
n /= base;
} while (n);
if (number < 0) {
end--;
*end = '-';
}
fputs(end, stdout);
return (int) (&buf[sizeof buf] - end - 1);
}
int main(void) {
printf(" %d\n", print_int(0, 10));
printf(" %d\n", print_int(INT_MAX, 36));
printf(" %d\n", print_int(INT_MIN, 2));
return 0;
}
Output
0 1
zik0zj 6
-10000000000000000000000000000000 33