You need to replace your while loop with a for loop, the number of iterations matching the number of digits you want.
It is better to write a helper function to do the conversion. For example:
Code:
/* Convert value to binary.
* buffer must have room for at least (digits + 1) chars.
*/
char *to_binary(char *const buffer, int digits, unsigned long value)
{
buffer[digits] = '\0';
while (digits-- > 0) {
buffer[digits] = '0' + (left & 1UL);
left /= 2UL;
}
return buffer;
}
To use this, you can do for example
Code:
int main(void)
{
char string[10];
int number;
number = 85;
printf("%d in decimal is %s in binary.\n", number, to_binary(string, 8, number));
return 0;
}