summaryrefslogtreecommitdiff
path: root/rushs/tinyprintf/my_atoi_base
diff options
context:
space:
mode:
Diffstat (limited to 'rushs/tinyprintf/my_atoi_base')
-rw-r--r--rushs/tinyprintf/my_atoi_base/my_atoi_base.c86
-rw-r--r--rushs/tinyprintf/my_atoi_base/my_atoi_base.h8
2 files changed, 94 insertions, 0 deletions
diff --git a/rushs/tinyprintf/my_atoi_base/my_atoi_base.c b/rushs/tinyprintf/my_atoi_base/my_atoi_base.c
new file mode 100644
index 0000000..46b4560
--- /dev/null
+++ b/rushs/tinyprintf/my_atoi_base/my_atoi_base.c
@@ -0,0 +1,86 @@
+#include "my_atoi_base.h"
+
+int val_in_base(char c, const char *base)
+{
+ size_t i;
+ for (i = 0; base[i] && base[i] != c; i++)
+ {
+ continue;
+ }
+
+ if (base[i])
+ {
+ return i;
+ }
+
+ return -1;
+}
+
+int base_size(const char *base)
+{
+ int res;
+ for (res = 0; base[res]; res++)
+ {
+ continue;
+ }
+ return res;
+}
+
+int my_atoi_base(const char *str, const char *base)
+{
+ int res = 0;
+
+ // str error check
+ if (str == NULL || *str == '0')
+ {
+ return 0;
+ }
+
+ // trim whitespaces
+ for (; *str && *str == ' '; str++)
+ {
+ continue;
+ }
+
+ // move to end of str
+ size_t l;
+ for (l = 0; str[l]; l++)
+ {
+ continue;
+ }
+ l--;
+
+ // prepare for calculations
+ int b = base_size(base);
+ int factor = 1;
+
+ // actual conversion of up to the second element of str (potential sign)
+ for (; l > 0; l--)
+ {
+ int val = val_in_base(str[l], base);
+ if (val == -1)
+ {
+ return 0;
+ }
+ res += val * factor;
+
+ factor *= b;
+ }
+
+ // l should be 0 by now
+ if (str[l] == '-')
+ {
+ return -res;
+ }
+ else if (str[l] != '+')
+ {
+ int val = val_in_base(str[l], base);
+ if (val == -1)
+ {
+ return 0;
+ }
+ return res + val * factor;
+ }
+
+ return res;
+}
diff --git a/rushs/tinyprintf/my_atoi_base/my_atoi_base.h b/rushs/tinyprintf/my_atoi_base/my_atoi_base.h
new file mode 100644
index 0000000..296ae23
--- /dev/null
+++ b/rushs/tinyprintf/my_atoi_base/my_atoi_base.h
@@ -0,0 +1,8 @@
+#ifndef MY_ATOI_BASE_H
+#define MY_ATOI_BASE_H
+
+#include <stddef.h>
+
+int my_atoi_base(const char *str, const char *base);
+
+#endif /* ! MY_ATOI_BASE_H */