aboutsummaryrefslogtreecommitdiff
path: root/strings.c
diff options
context:
space:
mode:
Diffstat (limited to 'strings.c')
-rw-r--r--strings.c73
1 files changed, 73 insertions, 0 deletions
diff --git a/strings.c b/strings.c
new file mode 100644
index 0000000..55aff97
--- /dev/null
+++ b/strings.c
@@ -0,0 +1,73 @@
+#include <stddef.h>
+
+#include "strings.h"
+
+void uint32_to_dec(uint32_t number, char buf[10])
+{
+ for (int i = 0; i < 10; i++)
+ {
+ buf[10 - 1 - i] = number % 10;
+ number /= 10;
+ }
+}
+
+void uint32_to_hex(uint32_t number, char buf[8])
+{
+ for (int i = 0; i < 8; i++)
+ {
+ unsigned char quadbit = (number >> ((8 - i - 1) * 4)) & 0xf;
+ buf[i] = quadbit > 9 ? quadbit - 10 + 'a' : quadbit + '0';
+ }
+}
+
+void uint32_to_bin(uint32_t number, char buf[32])
+{
+ for (int i = 0; i < 32; i++)
+ buf[i] = ((number >> (32 - i - 1)) & 1) ? '1' : '0';
+}
+
+void uint32_to_decstring(uint32_t number, char buf[11])
+{
+ uint32_to_dec(number, buf);
+ buf[10] = '\0';
+}
+
+void uint32_to_hexstring(uint32_t number, char buf[9])
+{
+ uint32_to_hex(number, buf);
+ buf[9] = '\0';
+}
+
+void uint32_to_binstring(uint32_t number, char buf[33])
+{
+ uint32_to_bin(number, buf);
+ buf[32] = '\0';
+}
+
+void trim_0s(char string[])
+{
+ size_t i;
+ for (i = 0; string[i] != '\0' && string[i] != '0'; i++);
+
+ size_t j = 0;
+
+ if (string[i] == '\0')
+ string[j++] = string[i--];
+
+ do
+ string[j] = string[i + j];
+ while (string[j++]);
+}
+
+void uint32_to_decstringt(uint32_t number, char buf[11])
+{
+ uint32_to_decstring(number, buf);
+ trim_0s(buf);
+}
+
+void uint32_to_hexstringt(uint32_t number, char buf[9])
+{
+ uint32_to_hexstring(number, buf);
+ trim_0s(buf);
+}
+