First draft of a kernel side library, string.h & string.c implementing itoa
This commit is contained in:
parent
50a3c8d1d9
commit
4512a93249
2 changed files with 46 additions and 0 deletions
39
lib/string.c
Normal file
39
lib/string.c
Normal file
|
@ -0,0 +1,39 @@
|
|||
char *itoa(int value, char *str, int base) {
|
||||
char *p = str;
|
||||
char *p1, *p2;
|
||||
unsigned int uvalue = value;
|
||||
int negative = 0;
|
||||
|
||||
if (base < 2 || base > 36) {
|
||||
*str = '\0';
|
||||
return str;
|
||||
}
|
||||
|
||||
if (value < 0 && base == 10) {
|
||||
negative = 1;
|
||||
uvalue = -value;
|
||||
}
|
||||
|
||||
// Convert to string
|
||||
do {
|
||||
int digit = uvalue % base;
|
||||
*p++ = (digit < 10) ? '0' + digit : 'a' + (digit - 10);
|
||||
uvalue /= base;
|
||||
} while (uvalue);
|
||||
|
||||
if (negative)
|
||||
*p++ = '-';
|
||||
|
||||
*p = '\0';
|
||||
|
||||
// Reverse string
|
||||
p1 = str;
|
||||
p2 = p - 1;
|
||||
while (p1 < p2) {
|
||||
char tmp = *p1;
|
||||
*p1++ = *p2;
|
||||
*p2-- = tmp;
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
7
lib/string.h
Normal file
7
lib/string.h
Normal file
|
@ -0,0 +1,7 @@
|
|||
#ifndef KERNEL_STRING_H
|
||||
#define KERNEL_STRING_H
|
||||
|
||||
/** Integer to ascii */
|
||||
char *itoa(int value, char *str, int base);
|
||||
|
||||
#endif
|
Loading…
Add table
Reference in a new issue