From 533d39b4c2c3bb29e032da99a0d73ceaf6d20fc6 Mon Sep 17 00:00:00 2001 From: Muhammet Asan Date: Thu, 14 Feb 2019 13:25:34 +0100 Subject: [PATCH] 10 times faster int to string implementation --- lv_misc/lv_math.c | 64 ++++++++++++++++------------------------------- 1 file changed, 22 insertions(+), 42 deletions(-) diff --git a/lv_misc/lv_math.c b/lv_misc/lv_math.c index a0d26053e..394246916 100644 --- a/lv_misc/lv_math.c +++ b/lv_misc/lv_math.c @@ -34,7 +34,7 @@ static int16_t sin0_90_table[] = { 28377, 28659, 28932, 29196, 29451, 29697, 29934, 30162, 30381, 30591, 30791, 30982, 31163, 31335, 31498, 31650, 31794, 31927, 32051, 32165, 32269, 32364, 32448, 32523, 32587, 32642, 32687, 32722, 32747, 32762, - 32767 + 32767 }; @@ -54,53 +54,33 @@ static int16_t sin0_90_table[] = { */ char * lv_math_num_to_str(int32_t num, char * buf) { - char * buf_ori = buf; - if(num == 0) { + if (num == 0) { buf[0] = '0'; buf[1] = '\0'; return buf; - } else if(num < 0) { - (*buf) = '-'; - buf++; - num = LV_MATH_ABS(num); } - uint32_t output = 0; - int8_t i; - - for(i = 31; i >= 0; i--) { - if((output & 0xF) >= 5) - output += 3; - if(((output & 0xF0) >> 4) >= 5) - output += (3 << 4); - if(((output & 0xF00) >> 8) >= 5) - output += (3 << 8); - if(((output & 0xF000) >> 12) >= 5) - output += (3 << 12); - if(((output & 0xF0000) >> 16) >= 5) - output += (3 << 16); - if(((output & 0xF00000) >> 20) >= 5) - output += (3 << 20); - if(((output & 0xF000000) >> 24) >= 5) - output += (3 << 24); - if(((output & 0xF0000000) >> 28) >= 5) - output += (3 << 28); - output = (output << 1) | ((num >> i) & 1); + int8_t digitCount = 0; + int8_t i = 0; + if (num < 0) { + buf[digitCount++] = '-'; + num = abs(num); + ++i; } - - uint8_t digit; - bool leading_zero_ready = false; - for(i = 28; i >= 0; i -= 4) { - digit = ((output >> i) & 0xF) + '0'; - if(digit == '0' && leading_zero_ready == false) continue; - - leading_zero_ready = true; - (*buf) = digit; - buf++; + while (num) { + char digit = num % 10; + buf[digitCount++] = digit + 48; + num /= 10; } - - (*buf) = '\0'; - - return buf_ori; + buf[digitCount] = '\0'; + digitCount--; + while (digitCount > i) { + char temp = buf[i]; + buf[i] = buf[digitCount]; + buf[digitCount] = temp; + digitCount--; + i++; + } + return buf; } /**