Decimal to Binary

后端 未结 12 1319
攒了一身酷
攒了一身酷 2020-12-01 13:08

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 alrea

12条回答
  •  青春惊慌失措
    2020-12-01 13:34

    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;
    }
    

提交回复
热议问题