From cc0dd226c6463ea9a8d0f39d256746a7f918a597 Mon Sep 17 00:00:00 2001 From: Jan Tattermusch Date: Wed, 9 Dec 2015 11:49:33 -0800 Subject: [PATCH] reimplement ltoa and int64toa without negation --- src/core/support/string.c | 34 ++++++++++++---------------------- 1 file changed, 12 insertions(+), 22 deletions(-) diff --git a/src/core/support/string.c b/src/core/support/string.c index ed000e33724..46a7ca3d462 100644 --- a/src/core/support/string.c +++ b/src/core/support/string.c @@ -153,9 +153,8 @@ void gpr_reverse_bytes(char *str, int len) { } int gpr_ltoa(long value, char *string) { - unsigned long uval; + long sign; int i = 0; - int neg = value < 0; if (value == 0) { string[0] = '0'; @@ -163,25 +162,20 @@ int gpr_ltoa(long value, char *string) { return 1; } - if (neg) { - uval = (unsigned long)-value; - } else { - uval = (unsigned long)value; + sign = value < 0 ? -1 : 1; + while (value) { + string[i++] = (char)('0' + sign * (value % 10)); + value /= 10; } - while (uval) { - string[i++] = (char)('0' + uval % 10); - uval /= 10; - } - if (neg) string[i++] = '-'; + if (sign < 0) string[i++] = '-'; gpr_reverse_bytes(string, i); string[i] = 0; return i; } int gpr_int64toa(gpr_int64 value, char *string) { - gpr_uint64 uval; + gpr_int64 sign; int i = 0; - int neg = value < 0; if (value == 0) { string[0] = '0'; @@ -189,16 +183,12 @@ int gpr_int64toa(gpr_int64 value, char *string) { return 1; } - if (neg) { - uval = (gpr_uint64)-value; - } else { - uval = (gpr_uint64)value; - } - while (uval) { - string[i++] = (char)('0' + uval % 10); - uval /= 10; + sign = value < 0 ? -1 : 1; + while (value) { + string[i++] = (char)('0' + sign * (value % 10)); + value /= 10; } - if (neg) string[i++] = '-'; + if (sign < 0) string[i++] = '-'; gpr_reverse_bytes(string, i); string[i] = 0; return i;