十进制转二进制 [英] Decimal to Binary

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

问题描述

我有一个数字,我想在 C 中转换为二进制(从十进制).

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?

我还希望二进制文件用 char *

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) = '';
  int mask = 0x10 << 1;
  while(mask >>= 1)
    *str++ = !!(mask & num) + '0';
}

在这里,我们首先确保字符串以空字符结尾.然后,我们创建一个带有单个掩码的掩码(它是您期望的掩码,向左移动一次以说明第一次运行时的移位).每次通过循环,掩码向右移动一位,然后将相应的字符设置为1"或0"(!! 确保我们正在添加'0' 的 0 或 1).最后,当掩码中的 1 移出数字时,while 循环结束.

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

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

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