Create a string in binary from a decimal number
Hi.
My first post here.
I am attempting to take a decimal number (0-255) and convert it to a binary string.
Something that looks like 0b01010101 for example.
Code:
//CONVERT DECIMAL TO BINARY FUNCTION
void tobinary(char str[11], int num)
{
int i;
bool bin;
str[0] = '0';
str[1] = 'b';
for (i=2; i<10; i++)
{
bin = (num & 0x80);
if (bin = 1)
{
str[i] = '1';
}
else
{
str[i] = '0';
}
num <<= 1;
}
str[i++] = '\0';
}
This is what i have written, but the string just comes out as 0b11111111, no matter what number i give it.
Not sure what i have done wrong. Is there anything obvious here to the more experienced eye?