How to convert Huge decimal value binary

56 views Asked by At

I have a simple program in which program receive input from the file and converts decimal to binary and counts number of ones in its binary form? Now For small values it is okay and for huge values like 15755645551 , it's obviously not working anyone has any idea how to resolve this problem? anyone can try with my code? thank you!! Here is my code:

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

There are 1 answers

0
lampv On

Because "long" type occupies 4 bytes as "int" type. You should change it to "long long" type.