小数为二进制 [英] Decimal to Binary

查看:151
本文介绍了小数为二进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数字,我想转换为二进制(十进制)的温度。

I have a number that I would like to convert to binary (from decimal) in C.

我想我的二进制始终处于5位(小数绝不会超过31个)。我已经有一个手工做它通过将功能,但就是很难垫它到5位。

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?

我也想二进制重新$ P $在的char * psented

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

下面,我们通过确保在空字符的字符串结尾开始。然后,我们创建了一个面具,在一个单一的一(它的你所期望的面具,转移到以考虑的条件,而第一次运行移位左一次)。通过每次循环中,掩模被移动一个位置到右侧,然后将相应的字符被设置为1或0(在 !! 确保我们加入无论是0或1 0 )。最后,当在掩模1被移出的数量,则同时循环结束。

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

这篇关于小数为二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆