I have a number that I would like to convert to binary (from decimal) in C.
I would like my binary to always be in 5 bits (the decimal will never exceed 31). I already have a function that does it manually by dividing but that is hard to pad it to 5 bits.
Is there any easier way? Perhaps using bitwise shift?
I would also like the binary to be represented in a char *
1001 in binary is 1111101001. Unlike the decimal number system where we use the digits 0 to 9 to represent a number, in a binary system, we use only 2 digits that are 0 and 1 (bits).
What is 5 in Binary? 5 in binary is 101. To find decimal to binary equivalent, divide 5 successively by 2 until the quotient becomes 0. The binary equivalent can be obtained by writing the remainder in each division step from the bottom to the top.
Here's an elegant solution:
void getBin(int num, char *str)
{
*(str+5) = '\0';
int mask = 0x10 << 1;
while(mask >>= 1)
*str++ = !!(mask & num) + '0';
}
Here, we start by making sure the string ends in a null character. Then, we create a mask with a single one in it (its the mask you would expect, shifted to the left once to account for the shift in the first run of the while conditional). Each time through the loop, the mask is shifted one place to the right, and then the corresponding character is set to either a '1' or a '0' (the !!
ensure that we are adding either a 0 or a 1 to '0'
). Finally, when the 1 in the mask is shifted out of the number, the while loop ends.
To test it, use the following:
int main()
{
char str[6];
getBin(10, str);
printf("%s\n", str);
return 0;
}
If you don't need leading zeroes, you can just use itoa(value, outputstring, base)
For example
char s[9];
itoa(10, s, 2);
printf("%s\n", s);
will print out
1010
Else you can just write a very simple function.
void tobin5str(int value, char* output)
{
int i;
output[5] = '\0';
for (i = 4; i >= 0; --i, value >>= 1)
{
output[i] = (value & 1) + '0';
}
}
int main()
{
char s[6];
tobin5str(10, s);
printf("%s\n", s);
return 0;
}
will print out
01010
A more generic approach can be a function that ask you how much bits to convert.
void tobinstr(int value, int bitsCount, char* output)
{
int i;
output[bitsCount] = '\0';
for (i = bitsCount - 1; i >= 0; --i, value >>= 1)
{
output[i] = (value & 1) + '0';
}
}
Of course bitsCount must be a value from 1 to 32, and the buffer string must be allocated for at least bitsCount + 1 characters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With