My question is based on this post: Decimal to Binary and the selected solution.
I can get the selected response code, but it only works for 5 bits. How to change this code to work with large numbers, for example 8 bits?
I tried just setting the character offset in the first line from 5 to 8, but failed.
void getBin(int num, char *str)
{
*(str+5) = '\0';
int mask = 0x10 << 1;
while(mask >>= 1)
*str++ = !!(mask & num) + '0';
}
and test with this code by adjusting 6-9 again according to the function above:
int main()
{
char str[6];
getBin(10, str);
printf("%s\n", str);
return 0;
}
but only the first five bits are still displayed, and then random characters are output. Can someone explain what exactly happens when I tweak these numbers so that I can get this to work for converting bits 8 (or any other size)?