【问题标题】:C decimal to binary converter (16 bits)C 十进制到二进制转换器(16 位)
【发布时间】:2017-01-18 17:48:12
【问题描述】:

我正在尝试将十进制数转换为二进制数(最多 16 位)。我的函数最多可完美运行 8 位,但当我想打印最多 16 位的数字时,它会停止打印字符。 我使用“int”作为 8 位的数据类型,但由于我想存储 16 位,所以我在每个变量中都使用了 unsigned long int。

代码如下:

/* Program to convert decimal to binary (16 bits) */

#include <stdio.h>
#include <string.h>

char *byte_to_binary_str(long unsigned int byte);

int main()
{

 printf("%s",byte_to_binary_str(32768));  //1000000 0000000
    return 0;
}

char *byte_to_binary_str(long unsigned int byte)
{
    static char bit_string[17];
    bit_string[0] = '\0';

    long unsigned int mask;
    for (mask = 2^15; mask > 0; mask >>= 1) {
        /* Check if the mask bit is set */
        strcat(bit_string, byte & mask ? "1" : "0");
    }

    return bit_string;
}

我的输出给了我:

0000
Process returned 0 (0x0)   execution time : 0.063 s
Press any key to continue.

有人知道为什么会这样吗?提前致谢。

【问题讨论】:

  • 2^15 并不意味着您认为的那样。 See this chart实际上做了什么。
  • pow(2,15) :新的、更昂贵的写作方式32768
  • 你足够聪明,可以理解右移,但还不足以理解左移?
  • pow 可能针对这种情况进行了优化。但无论如何,只要有一个明确的常量0x8000(0x1&lt;&lt;15) 就可以说更好。
  • @JohnBollinger:或者更合适的uint_least16_t

标签: c binary decimal


【解决方案1】:
mask = 2^15;

不会将 mask 的值设置为您所期望的值 2^15 不是 2 的 15 次幂。它是 215 的按位异或。

您需要二进制形式的 1000 0000 0000 0000。该数字将是十六进制的0x8000。因此,使用:

mask = 0x8000;

您还可以在算法中使用有意义的东西。

mask = 1u << 15;

【讨论】:

  • 由于OP的系统可能有16位int/unsigned,最好使用1u &lt;&lt; 15
猜你喜欢
  • 2013-05-14
  • 2011-02-19
  • 1970-01-01
  • 1970-01-01
  • 2017-05-22
  • 2019-07-18
  • 2016-08-26
  • 1970-01-01
  • 2020-06-27
相关资源
最近更新 更多