Hello Gustavo,
Yes, there are many variations on this theme.
Irrespective of whether a hardware divider is available, your approach to deriving the remainder of each division is very likely to be more efficient. This is because you have a single explicit division only. With my previous aproach, there is likely to be two divisions - an implicit one for the '%' operator implementation, plus the explicit one. But this will depend on the compiler optimisation process.
I notice that the local variable is declared as type INT8U, presumably unsigned. I might have expected this would need to be a signed type for the second decrementing loop to exit, when there is a 5-digit result.
If using a buffer that is external to the conversion function, it may provide more flexibility and efficiency if the buffer initialisation also occurs outside the function. This is especially so if the function is called to "fill in the blanks" of a larger string. For example -
void disp_temp( int temp){ char buffer[] = "Temperature: 0 C"; // Initialise local variable conv_decimal( temp, &buffer[11]); LCD_puts( buffer);}
The following is a proposed adaption to allow the handling of a signed value. In this case, the local variable 'i' can be unsigned, since the loop exit does not require a negative value.
void conv_decimal(INT16 val, CHAR8 *buff){ INT16U backup; INT8U i; CHAR8 s = ' '; // Fill buffer with spaces for (i = 0; i < 6; i++) { *(buff + i) = ' '; } // Null termination for data *(buff + i) = 0; if (val < 0) { val = -val; s = '-'; } // Convert binary value to decimal ASCII for (i = 5; i > 0; i--) { backup = val; val /= 10; *(buff + i) = (backup - (val*10)) + '0'; if (val == 0) break; } *(buff + i) = s; // Sign character}
Regards,
Mac