diff options
author | Chase Douglas <chase.douglas@canonical.com> | 2012-04-06 10:13:45 -0700 |
---|---|---|
committer | Peter Hutterer <peter.hutterer@who-t.net> | 2012-06-21 15:45:22 +1000 |
commit | 704b847abfd29e9adde27127a15a963414f8bcf4 (patch) | |
tree | 5e2b29d8d65f6aff9dfae92f30357b82e480edd3 /os | |
parent | bc85c81687a24aea738094ff11f4448fb3b3afbb (diff) |
Add FormatUInt64{,Hex}() for formatting numbers in a signal safe manner
Signed-off-by: Chase Douglas <chase.douglas@canonical.com>
Reviewed-by: Peter Hutterer <peter.hutterer@who-t.net>
Signed-off-by: Peter Hutterer <peter.hutterer@who-t.net>
Diffstat (limited to 'os')
-rw-r--r-- | os/utils.c | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/os/utils.c b/os/utils.c index 2f0754886..998c3ed4a 100644 --- a/os/utils.c +++ b/os/utils.c @@ -1793,3 +1793,47 @@ xstrtokenize(const char *str, const char *separators) free(list); return NULL; } + +/* Format a number into a string in a signal safe manner. The string should be + * at least 21 characters in order to handle all uint64_t values. */ +void +FormatUInt64(uint64_t num, char *string) +{ + uint64_t divisor; + int len; + int i; + + for (len = 1, divisor = 10; + len < 20 && num / divisor; + len++, divisor *= 10); + + for (i = len, divisor = 1; i > 0; i--, divisor *= 10) + string[i - 1] = '0' + ((num / divisor) % 10); + + string[len] = '\0'; +} + +/* Format a number into a hexadecimal string in a signal safe manner. The string + * should be at least 17 characters in order to handle all uint64_t values. */ +void +FormatUInt64Hex(uint64_t num, char *string) +{ + uint64_t divisor; + int len; + int i; + + for (len = 1, divisor = 0x10; + len < 16 && num / divisor; + len++, divisor *= 0x10); + + for (i = len, divisor = 1; i > 0; i--, divisor *= 0x10) { + int val = (num / divisor) % 0x10; + + if (val < 10) + string[i - 1] = '0' + val; + else + string[i - 1] = 'a' + val - 10; + } + + string[len] = '\0'; +} |