void getBin(int num, char *str)
{
*(str+8) = '\0';
int mask = 0x80 << 1;
while(mask >>= 1)
*str++ = !!(mask & num) + '0';
}
main()
{
char str[9];
getBin(254, str);
printf("%s\n", str);
return 0;
}
For 8-bit number you need array of 9 chars. Also you need to change mask, so it can mask all bits.
The mask for the most significant bit for a 5-bit number like 11111
is 10000
which is equal to 16
decimal or 10
hexadecimal.
Same thing for 8-bit number. The mask is 10000000
. Since the loop start with mask >>= 1
the mask is shifted one to left int mask = 0x10 << 1;
to compensate.
Thus to modify it for a x-bit
number, define an array of x+1
chars. Put \0
at index x
. Find the x-bit
number where the most significant bit of it is 1
and others are 0
. The number is 2^(x-1)
(2 power (x-1)).