char * a_string = malloc(128);
snprintf(a_string, 128, "%u", a);
See the man pages for printf(3) for more information.
In short, printf
and friends take a format string that can contain a bunch of placeholders that signify the formatting of the arguments to follow. In the above, we just use %u
, which is the format placeholder for an unsigned int
. With sprintf
we write the result to the buffer in the first argument (a_string
) instead of to standard output.
The snprintf
variant is for safety, to guarantee that we do not write more than the buffer size (here 128
, but you should think about what you want in general). Since C strings are null-terminated, it does not matter that we don't use all of the buffer size. Code interpreting a_string
as a string will not consider more of the buffer than what was written by snprintf
.
Missing from this answer is error handling: if snprintf
returns a value of at least the size argument (here 128
), then it had to truncate its output. If it returns negative, an error occurred. You'll want to deal with these cases.
PS: If you're in an embedded setting, and you know the size of the output string at compile time (which you probably know since you know the size of unsigned short
), you'll probably want to use an array on the stack for the string buffer instead of heap allocating it.