Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fmt: add str_itoa #569

Merged
merged 1 commit into from
Oct 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions include/re_fmt.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
#include <stdarg.h>
#include <stdio.h>

enum {
ITOA_BUFSZ = 34,
};

struct mbuf;

Expand Down Expand Up @@ -117,6 +120,7 @@ int str_cmp(const char *s1, const char *s2);
int str_casecmp(const char *s1, const char *s2);
size_t str_len(const char *s);
const char *str_error(int errnum, char *buf, size_t sz);
char *str_itoa(uint32_t val, char *buf, int base);


/**
Expand Down
28 changes: 28 additions & 0 deletions src/fmt/str.c
Original file line number Diff line number Diff line change
Expand Up @@ -219,3 +219,31 @@ int str_bool(bool *val, const char *str)

return err;
}


/**
* Converts unsigned integer to string
*
* @param val Number to be converted
* @param buf Buffer[ITOA_BUFSZ] that holds the result of the conversion
* @param base Base to use for conversion
*
* @return Pointer to buffer
*/
char *str_itoa(uint32_t val, char *buf, int base)
{
int i = ITOA_BUFSZ - 2;

buf[ITOA_BUFSZ - 1] = '\0';

if (!val) {
buf[i] = '0';
return &buf[i];
}

for (; val && i; --i, val /= base)
buf[i] = "0123456789abcdef"[val % base];

return &buf[i + 1];
}