update math with itoa base

This commit is contained in:
hugogogo
2025-03-15 18:34:10 +01:00
parent ec928d14b1
commit bd23d89706
6 changed files with 59 additions and 15 deletions

View File

@@ -30,3 +30,35 @@ void int_to_string(uint64_t value, char *buffer) {
size--;
}
}
void itoa_base(uint64_t value, char *buffer, uint8_t base) { // buffer must have the right size
if (base < 2 || base > 36) {
buffer[0] = '\0'; // unsupported base
return;
}
// handle zero case
if (value == 0) {
buffer[0] = '0';
buffer[1] = '\0';
return;
}
uint8_t size = 0;
uint64_t copy = value;
while (copy) {
copy /= base;
size++;
}
buffer[size] = '\0'; // null-terminate the string
size--; // adjust index for last digit
while (value) {
uint8_t digit = value % base;
buffer[size] = digit < 10 ? ('0' + digit) : ('A' + digit - 10);
value /= base;
size--;
}
}