diff options
author | Freya Murphy <freya@freyacat.org> | 2025-04-03 12:30:34 -0400 |
---|---|---|
committer | Freya Murphy <freya@freyacat.org> | 2025-04-03 12:30:34 -0400 |
commit | ec3c37d1d40d7b288584c234f4c3e7a600f2353d (patch) | |
tree | bb587b33c4c793ff7a3317dfa958d69b0fa318a1 /lib/btoa.c | |
parent | move boot only headers to boot (diff) | |
download | comus-ec3c37d1d40d7b288584c234f4c3e7a600f2353d.tar.gz comus-ec3c37d1d40d7b288584c234f4c3e7a600f2353d.tar.bz2 comus-ec3c37d1d40d7b288584c234f4c3e7a600f2353d.zip |
new libs
Diffstat (limited to 'lib/btoa.c')
-rw-r--r-- | lib/btoa.c | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/lib/btoa.c b/lib/btoa.c new file mode 100644 index 0000000..fe5e275 --- /dev/null +++ b/lib/btoa.c @@ -0,0 +1,43 @@ +#include <stdlib.h> + +static char suffixes[] = { 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'R', 'Q' }; + +char *btoa(size_t bytes, char *buf) +{ + // no suffix if under 1K, print up to four digits + if (bytes < 1024) { + ultoa(bytes, buf, 10); + return buf; + } + + // store one digit of remainder for decimal + unsigned int remainder; + // power of 1024 + int power = 0; + + // iterate until remaining bytes fits in three digits + while (bytes >= 1000) { + remainder = (bytes % 1024) * 10 / 1024; + bytes /= 1024; + power += 1; + } + + // end of number + char *end; + + if (bytes >= 10) { + // no decimal + end = ultoa(bytes, buf, 10); + } else { + // decimal + end = ultoa(bytes, buf, 10); + end[0] = '.'; + end = ultoa(remainder, end + 1, 10); + } + + // add suffix + end[0] = suffixes[power - 1]; + end[1] = '\0'; + + return buf; +} |