Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Source code in embedded C for unsigned integer to string

Tags:

c

embedded

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.

like image 221
riscy Avatar asked Nov 15 '25 13:11

riscy


1 Answers

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.

like image 135
R.. GitHub STOP HELPING ICE Avatar answered Nov 18 '25 06:11

R.. GitHub STOP HELPING ICE