Not that I do not find interesting the other solutions, and it is my humble monkey way of working... always very near of the assembly code ... in the previous solutions, there is way too many variables created to achieve the goal.. in my exemple, only 2 variables are created, a string: result, an int8_t: n, plus a parameter in the function declaration, so the milliseconds are passed to the function using a INT: value
#include <string>
using namespace std;
// milliseconds to DDD HH:MM:SS.mmm , days are displayed if > 0
string ToDDHHMMSSmmm(int value)
{
string result=""; uint8_t n=value/86400000;
if (n>0) {result=to_string(n)+' ';}
value-=86400000*n; n=value/3600000; if(n<10) result+='0';
result+=to_string(n); value-=3600000*n;
n=value/60000; result+=':'; if(n<10) result+='0';
result+=to_string(n); value-=60000*n;
n=value/1000; result+=':'; if(n<10) result+='0';
result+=to_string(n); value-=1000*n;
result+='.'; if(value<100) result+='0';
if(value<10) result+='0';
result+=to_string(value);
return result;
}
1- a string result is created empty
2- a byte (8 bit int) is created(n) as the milliseconds passed to the
int parameter named value is divided by 86400000 (representing
the quantity of millisec per day)
3- if n is greater than 0, the numbers of days(max 255 days !) is added
to the string result.
4- using the same variables, n(the previously calculated days) will be
multiplied by the same number, and the result is subtracted from the
variable value. now n is set to the value divided by 3600000.
5- if n<10, we have only one digit for the hours, so add a char '0' to
the string result.
6- and convert + add to the string the value of n.
7- same principle for the minutes, the seconds, and the last part
the 3 digit milliseconds.
8- the string is built as the calculation are done, and the return
string is always in the perfect format (DDD) HH:MM:SS.mmm
The bytes used are as follow int32 for the value 4
int8 for the work 1
String 13 to 16 max (if days > 0)
...for a total of 21 Bytes, the large numbers are never stored in variables, they remain in the code and are calculated in the register of the cpu or mcu only. To be even nearer of ASSEMBLY, I should not used std::string and std::to_string, instead, pointers and using 0x20 for spaces, 0x3a for semi colons, and adding 0x30 to any digit values to create the ASCII directly in memory.