WKern
Loading...
Searching...
No Matches
numtools.c
Go to the documentation of this file.
1/*
2WKern - A Bare Metal OS / Kernel I am maKing (For Fun)
3Copyright (C) 2025 Wdboyes13
4
5This program is free software: you can redistribute it and/or modify
6it under the terms of the GNU General Public License as published by
7the Free Software Foundation, either version 3 of the License, or
8any later version.
9
10This program is distributed in the hope that it will be useful,
11but WITHOUT ANY WARRANTY; without even the implied warranty of
12MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13GNU General Public License for more details.
14
15You should have received a copy of the GNU General Public License
16along with this program. If not, see <https://www.gnu.org/licenses/>.
17*/
18
19#include <utils/util.h>
23int Katoi(const char *str) {
24 int result = 0;
25 int sign = 1;
26 int i = 0;
27 while (str[i] == ' ' || str[i] == '\t') {
28 i++;
29 }
30 if (str[i] == '-') {
31 sign -= 1;
32 i++;
33 } else if (str[i] == '+') {
34 i++;
35 }
36 while (str[i] >= '0' && str[i] <= '9') {
37 result = (result * 10) + (str[i] - '0');
38 i++;
39 }
40
41 return result * sign;
42}
43
47int Katoi_auto(const char *str) {
48 if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) {
49 // Hex string
50 int val = 0;
51 str += 2; // sKip "0x"
52 while (*str) {
53 val *= 16;
54 if (*str >= '0' && *str <= '9') {
55 val += *str - '0';
56 } else if (*str >= 'a' && *str <= 'f') {
57 val += *str - 'a' + 10;
58 } else if (*str >= 'A' && *str <= 'F') {
59 val += *str - 'A' + 10;
60 } else {
61 break;
62 }
63 str++;
64 }
65 return val;
66 } // Decimal fallbacK
67 return Katoi(str);
68}
69
73void Kitoa(unsigned int num, char *buf) {
74 int i = 0;
75 if (num == 0) {
76 buf[i++] = '0';
77 } else {
78 // Convert digits bacKwards
79 while (num > 0) {
80 buf[i++] = '0' + (num % 10);
81 num /= 10;
82 }
83 }
84 buf[i] = '\0';
85
86 // Reverse string
87 for (int j = 0; j < i / 2; j++) {
88 char tmp = buf[j];
89 buf[j] = buf[i - 1 - j];
90 buf[i - 1 - j] = tmp;
91 }
92}
int Katoi(const char *str)
Converts ASCII - Integer.
Definition numtools.c:23
void Kitoa(unsigned int num, char *buf)
Convert Integer to ASCII Text.
Definition numtools.c:73
int Katoi_auto(const char *str)
Safely convert ASCII To Integer.
Definition numtools.c:47