54 lines
1.5 KiB
C
54 lines
1.5 KiB
C
/**
|
|
* uitoa implementation of Asagiri
|
|
* Copyright (C) 2023 Asagiri contributors
|
|
*
|
|
* This program is free software: you can redistribute it and/or modify
|
|
* it under the terms of the GNU General Public License as published by
|
|
* the Free Software Foundation, either version 3 of the License, or
|
|
* (at your option) any later version.
|
|
*
|
|
* This program is distributed in the hope that it will be useful,
|
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
* GNU General Public License for more details.
|
|
*
|
|
* You should have received a copy of the GNU General Public License
|
|
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
*/
|
|
|
|
#include <stdint.h>
|
|
|
|
static const char *digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
|
|
char *uitoa(uint32_t value, char *buffer, int base) {
|
|
if (base < 2 || base > 36) {
|
|
return buffer;
|
|
}
|
|
|
|
uint8_t index = 0;
|
|
uint8_t digit = 0;
|
|
|
|
/* Put base remainder of value into the buffer
|
|
* while dividing value by base */
|
|
do {
|
|
digit = value % base;
|
|
buffer[index] = digits[digit];
|
|
++index;
|
|
value /= base;
|
|
} while (value);
|
|
|
|
/* Null terminate */
|
|
buffer[index] = 0;
|
|
|
|
/* Reverse the buffer */
|
|
uint8_t len = index;
|
|
char temp = 0;
|
|
for (uint8_t i = 0; i < len >> 1; ++i) {
|
|
temp = buffer[i];
|
|
buffer[i] = buffer[len - i - 1];
|
|
buffer[len - i - 1] = temp;
|
|
}
|
|
|
|
return buffer;
|
|
}
|