I need to generate a path string from a number (in C)
e.g:
53431453 -> 0003/2F4/C9D
what I have so far is this:
char *id_to_path(long long int id, char *d)
{
char t[MAX_PATH_LEN];
sprintf(t, "%010llX", id);
memcpy(d, t, 4);
memcpy(d+5, t+4, 3);
memcpy(d+9, t+7, 4);
d[4] = d[8] = '/';
return d;
}
I’m wondering if there’s a better way, e.g to generate the final string in one step instead of doing sprintf and then moving the bytes around.
Thanks
Edit:
I benchmarked the given solutions
results in operations per second (higher is better):
(1) sprintf + memcpy : 3383005
(2) single sprintf : 2219253
(3) not using sprintf : 10917996
when compiling with -O3 the difference is even greater:
(1) 4422101
(2) 2207157
(3) 178756551
Since this function will be called a lot, I’ll use the fastest solution even though the single sprintf is the shortest and most readable.
Thanks for your answers!
Since the string uses hex, it can be quite easily done using shift and bit operators.
Getting the 4 highest bits from the value can be done like this:
Converting this to a digit simply means adding the character ‘0’ to it, like this:
However, since A, B, C, … don’t immediately follow the character 9, we have to perform an additional check, something like:
If we want the next 4 bits, we should only shift 24 bits, but then we still have the highest 4 bits left, so we should mask them out, like this:
If we pour this into your function, we get this:
Now adjust this to add the slashes in between, the extra zeroes in the beginning, …
EDIT:
I know this is not in one step, but it is better extensible if you later want to change the places of the slashes, …