Add baseconv_digits to the API

This commit is contained in:
Juhani Krekelä 2022-11-21 00:36:16 +02:00
parent 341f08d704
commit ebec133018
2 changed files with 22 additions and 4 deletions

View File

@ -3,13 +3,16 @@
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
static const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
bool baseconv(char outbuf[], size_t bufsize, unsigned base, uintmax_t num) {
static bool baseconv_internal(
char outbuf[], size_t bufsize,
const char *digits, unsigned base,
uintmax_t num
) {
// Supported bases are 2 to 36 inclusive (though it could be higher
// if our digits string was longer
if (base < 2 || base > sizeof(digits))
if (base < 2 || base > strlen(digits))
return false;
// Longest possible converted string is base-2, where we produce one
@ -45,3 +48,17 @@ bool baseconv(char outbuf[], size_t bufsize, unsigned base, uintmax_t num) {
return true;
}
bool baseconv(char outbuf[], size_t bufsize, unsigned base, uintmax_t num) {
const char *digits = "0123456789abcdefghijklmnopqrstuvwxyz";
return baseconv_internal(outbuf, bufsize, digits, base, num);
}
bool baseconv_digits(
char outbuf[], size_t bufsize,
const char *digits,
uintmax_t num
) {
size_t base = strlen(digits);
return baseconv_internal(outbuf, bufsize, digits, base, num);
}

View File

@ -1 +1,2 @@
bool baseconv(char outbuf[], size_t bufsize, unsigned base, uintmax_t num);
bool baseconv_digits(char outbuf[], size_t bufsize, const char *digits, uintmax_t num);