riscy riscy - 14 days ago 5
C Question

Source code in embedded C for unsigned integer to string

Without resorting to standard library utoa, I'm looking for source code of utoa so I may customise it for specific project. I have unsigned integer (32 bits) with output such as 0xFFFF_FFFF

I also looking for source code for unsigned integer and half word to string in binary format.

R.. R..
Answer

Try this:

char *dec(unsigned x, char *s)
{
    *--s = 0;
    if (!x) *--s = '0';
    for (; x; x/=10) *--s = '0'+x%10;
    return s;
}

You call it with a pointer to the end of a caller-provided buffer, and the function returns the pointer to the beginning of the string. The buffer should have length at least 3*sizeof(int)+1 to be safe.

Of course this is easily adapted to other bases.