【问题标题】:Convert a binary number from type short into a decimal number in C在C中将二进制数从short类型转换为十进制数
【发布时间】:2021-05-26 13:39:25
【问题描述】:

我需要从文件中读取一个二进制数,该二进制数用 C 语言中的 short 类型表示。

这个数字代表一个数组的大小,所以读完之后我想用这个数字作为十进制值。

我试图将二进制数转换为十进制,但我得到了错误的值。

例如:如果文件中的二进制数是 0000000000000101 ,十进制的大小应该是 5 但是当我使用“经典”二进制到十进制时,我得到的值是 17。

“经典”功能:

void main()
{
    int  num, binary_val, decimal_val = 0, base = 1, rem;
 
    printf("Enter a binary number(1s and 0s) \n");
    scanf("%d", &num); 
    binary_val = num;
    while (num > 0)
    {
        rem = num % 10;
        decimal_val = decimal_val + rem * base;
        num = num / 10 ;
        base = base * 2;
    }
    printf("The Binary number is = %d \n", binary_val);
    printf("Its decimal equivalent is = %d \n", decimal_val);
}

当我输入最后 3 个数字 (101) 时,我得到值 5,但当我输入完整数字 (0000000000000101) 时,我得到 17。

有什么想法可以解决这个问题吗?我在这里错过了什么?

谢谢

【问题讨论】:

  • Couldn't reproduce。你的编译器是什么?
  • 看起来您的编译器(或其标准库)已损坏,因为 scanf() 中的 %d 被定义为读取十进制整数(如以 10 为底的 strtol),但您的编译器库看起来将数字从零开始视为八进制,这是%i 格式说明符的规范。我的意见是你应该扔掉损坏的编译器并使用另一个编译器。
  • 你应该做的是读入一个字符串并使用strtol和base 2来转换它。

标签: c binary short


【解决方案1】:

这个例子如你所愿。

#include <math.h>
#include <stdio.h>
int convert(long long n);
int main() {
    long long n;
    printf("Enter a binary number: ");
    scanf("%lld", &n);
    printf("%lld in binary = %d in decimal", n, convert(n));
    return 0;
}
int convert(long long n) {
    int dec = 0, i = 0, rem;
    while (n != 0) {
        rem = n % 10;
        n /= 10;
        dec += rem * pow(2, i);
        ++i;
    }
    return dec;
}

【讨论】:

  • OP 的base = base * 2; 是一种比pow(2, i) 涉及浮点问题更好的方法。在这里使用窄的 int dec 几乎没有区别,但会使用更宽的整数类型。
猜你喜欢
  • 2020-10-27
  • 1970-01-01
  • 2014-04-21
  • 2020-09-10
  • 2020-04-28
  • 2011-01-08
  • 2010-12-08
  • 1970-01-01
  • 2012-12-26
相关资源
最近更新 更多