mirror of
https://github.com/UpsilonNumworks/Upsilon.git
synced 2026-01-18 16:27:34 +01:00
Bootloader pre-release
This commit is contained in:
@@ -24,6 +24,7 @@ liba_src += $(addprefix liba/src/, \
|
||||
strlcpy.c \
|
||||
strlen.c \
|
||||
external/sqlite/mem5.c \
|
||||
itoa.c \
|
||||
)
|
||||
|
||||
liba_src += $(addprefix liba/src/external/openbsd/, \
|
||||
|
||||
@@ -10,6 +10,7 @@ void free(void *ptr);
|
||||
void * malloc(size_t size);
|
||||
void * realloc(void *ptr, size_t size);
|
||||
void * calloc(size_t count, size_t size);
|
||||
char * itoa(int value, char *str, int base);
|
||||
|
||||
void abort(void) __attribute__((noreturn));
|
||||
|
||||
|
||||
60
liba/src/itoa.c
Normal file
60
liba/src/itoa.c
Normal file
@@ -0,0 +1,60 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
// https://www.techiedelight.com/implement-itoa-function-in-c/
|
||||
|
||||
// Function to swap two numbers
|
||||
void swap(char *x, char *y) {
|
||||
char t = *x; *x = *y; *y = t;
|
||||
}
|
||||
|
||||
// Function to reverse `buffer[i…j]`
|
||||
char* reverse(char *buffer, int i, int j) {
|
||||
while (i < j) {
|
||||
swap(&buffer[i++], &buffer[j--]);
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
// Iterative function to implement `itoa()` function in C
|
||||
char* itoa(int value, char* buffer, int base) {
|
||||
// invalid input
|
||||
if (base < 2 || base > 32) {
|
||||
return buffer;
|
||||
}
|
||||
|
||||
// consider the absolute value of the number
|
||||
int n = abs(value);
|
||||
|
||||
int i = 0;
|
||||
while (n) {
|
||||
int r = n % base;
|
||||
|
||||
if (r >= 10) {
|
||||
buffer[i++] = 65 + (r - 10);
|
||||
}
|
||||
else {
|
||||
buffer[i++] = 48 + r;
|
||||
}
|
||||
|
||||
n = n / base;
|
||||
}
|
||||
|
||||
// if the number is 0
|
||||
if (i == 0) {
|
||||
buffer[i++] = '0';
|
||||
}
|
||||
|
||||
// If the base is 10 and the value is negative, the resulting string
|
||||
// is preceded with a minus sign (-)
|
||||
// With any other base, value is always considered unsigned
|
||||
if (value < 0 && base == 10) {
|
||||
buffer[i++] = '-';
|
||||
}
|
||||
|
||||
buffer[i] = '\0'; // null terminate string
|
||||
|
||||
// reverse the string and return it
|
||||
return reverse(buffer, 0, i - 1);
|
||||
}
|
||||
Reference in New Issue
Block a user