My question is based on this post: Decimal to Binary and it\'s chosen solution.
I can get the chosen answer code working, but it only works for 5 bits. How do I modi
After accept answer.
Too many magic numbers.
In the original, there are constants 5
, 0x10
, 6
that do not show there relationship to the goal of a 5
binary digit number.
Then when going to 8, the constants 8
, 0x10
, 9
were used. Since 0x10
was not adjusted, code failed.
Instead approach the problem with a more general point-on-view and use code that eliminates or better expresses these magic numbers.
#define BitWidth 5
void getBin(int num, char *str)
{
int mask = 1 << (BitWidth - 1);
// skip the original shift left and then immediately shift right
do {
*str++ = !!(mask & num) + '0';
} while (mask >>= 1);
*str = '\0'; // by appending at the end, no need for a magic number
}
int main()
{
char str[BitWidth + 1];
getBin(10, str);
printf("%s\n", str);
return 0;
}
Note: the above approach (and other answers) have a problem when BitWidth
matches the int
width. But that is another issue easily solved by using unsigned
math.