I have a number that I would like to convert to binary (from decimal) in C.
I would like my binary to always be in 5 bits (the decimal will never exceed 31). I alrea
For 31 values, instead of doing malloc to allocate a string, followed by the bit manipulation to fill it, you may just want to use a lookup table.
static const char *bitstrings[] = {
"00000", "00001", "00010", … "11111"
};
Then your conversion is as simple as return bitstrings[i]. If you're doing this often, this will be faster (by avoiding malloc).
Otherwise, you don't really need any shifting (except to make writing your constants easier); you can just use bit-and:
char *bits = malloc(6);
bits[0] = (i & (1<<4)) ? '1' : '0'; /* you can also just write out the bit values, but the */
bits[1] = (i & (1<<3)) ? '1' : '0'; /* compiler should be able to optimize a constant! */
⋮
bits[6] = 0; /* null-terminate string*/
There is a (maybe) micro-optimization you can do if you assume ASCII, by using addition. You can also use a loop here, but I needed two lines for the comment :-P. Performance-wise, neither will matter. All the time is spent in malloc.