【问题标题】:How to convert Huge decimal value binary如何转换巨大的十进制值二进制
【发布时间】:2017-05-19 17:44:31
【问题描述】:

我有一个简单的程序,其中程序从文件接收输入并将十进制转换为二进制并计算二进制形式的个数? 现在对于小值没关系 对于像 15755645551 这样的巨大值,它显然不起作用 有人知道如何解决这个问题吗? 任何人都可以尝试使用我的代码? 谢谢!! 这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#define BUFFER 25

long number_read = 0;
long number_of_ones = 0;
long remainder_value = 0;
long binary = 0;
long base = 0;
long buff[BUFFER];

int main()
{
    FILE *fp;                 //file pointer fp
    fp = fopen("File.txt", "r+");

    while (fgets(buff, sizeof(buff), fp) != NULL)
    {
        number_read = atoi(buff);                   //ASCII to integer
        printf("\nnumber is=%d", number_read);
        while (number_read > 0)
        {
            remainder_value = number_read % 2;
            /*  To count no.of 1s */
            if (remainder_value == 1)
            {
                number_of_ones++;
            }

            binary = binary + remainder_value * base;
            number_read = number_read / 2;
            base = base * 10;
        }
        printf("\nNo.of 1's in It's binary representation is = %d\n", number_of_ones);
        number_of_ones = 0;
    }
    fclose(fp);
    return 0;
}

【问题讨论】:

  • 你知道15755645551 可能不适合long吗?
  • 是的..其实我已经用long试过了,上面忘了说..需要试试long long

标签: c file binary file-handling decimalformat


【解决方案1】:

因为“long”类型占用4个字节作为“int”类型。您应该将其更改为“long long”类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    • 2017-07-15
    • 2012-10-26
    • 2018-10-20
    • 2019-01-23
    • 2011-10-11
    • 2019-06-10
    相关资源
    最近更新 更多