darksky darksky - 10 months ago 55
C Question

Decimal to Binary

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 *


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;