From c95507881acb0d8cdaf7e0a29f445ee2fdaa2c80 Mon Sep 17 00:00:00 2001 From: antirez Date: Fri, 27 Feb 2015 15:20:58 +0100 Subject: [PATCH] Utils: added function to get radix 10 string length of signed integer. --- src/util.c | 12 ++++++++++++ src/util.h | 2 ++ 2 files changed, 14 insertions(+) diff --git a/src/util.c b/src/util.c index 4190775b..4b1aaaba 100644 --- a/src/util.c +++ b/src/util.c @@ -251,6 +251,18 @@ uint32_t digits10(uint64_t v) { return 12 + digits10(v / 1000000000000UL); } +/* Like digits10() but for signed values. */ +uint32_t sdigits10(int64_t v) { + if (v < 0) { + /* Abs value of LLONG_MIN requires special handling. */ + uint64_t uv = (v != LLONG_MIN) ? + -v : ((uint64_t) LLONG_MAX)+1; + return digits10(uv)+1; /* +1 for the minus. */ + } else { + return digits10(v); + } +} + /* Convert a long long into a string. Returns the number of * characters needed to represent the number. * If the buffer is not big enough to store the string, 0 is returned. diff --git a/src/util.h b/src/util.h index 666042c9..544b9b8b 100644 --- a/src/util.h +++ b/src/util.h @@ -35,6 +35,8 @@ int stringmatchlen(const char *p, int plen, const char *s, int slen, int nocase); int stringmatch(const char *p, const char *s, int nocase); long long memtoll(const char *p, int *err); +uint32_t digits10(uint64_t v); +uint32_t sdigits10(int64_t v); int ll2string(char *s, size_t len, long long value); int string2ll(const char *s, size_t slen, long long *value); int string2l(const char *s, size_t slen, long *value);