Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

c - 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 *

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's an elegant solution:

void getBin(int num, char *str)
{
  *(str+5) = '';
  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
", str);
  return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...