Home > Enterprise >  program to convert decimal to binary is not working for large outputs
program to convert decimal to binary is not working for large outputs

Time:10-10

I made a program to convert decimal to binary but it is not working for big outputs. I think I am not able to use long long int in my function properly.

Here is my code:

#include<iostream>
using namespace std;

int decimal_to_binary(int n)
{
    int x=1;
    long long int ans=0;
    while (x<=n){
        x*=2;
    }
    x/=2;
    while(x>0)
    {
        int lastdigit=n/x;
        n-=lastdigit*x;
        x/=2;
        ans=ans*10 lastdigit;
    }
    return ans;
}

int main()
{
    int input;
    long long int a;
    cout<<"input = ";
    cin>>input;
    a=decimal_to_binary(input);
    cout<<a;
}

For example, if I input 30 it gives me expected output i.e. 11111.

The program gives correct output up to 1023 input, but after that it gives me unexpected value. For example, if I input 1200 then output is 1420175408.

CodePudding user response:

You're storing a decimal number which is the binary representation of n reinterpreted as decimal.

If n>2047, ans will overflow a std::int32_t; if n>524287, ans will overflow a std::int64_t (the biggest signed 64-bit number is 9223372036854775807; unsigned would allow one more bit in ans).

The proper thing to return is a string. Try this:

std::string decimal_to_binary(int n)
{
    int x=1;
    std::string ans;
    while (x<=n){
        x*=2;
    }
    x/=2;
    while(x>0)
    {
        int lastdigit=n/x;
        n-=lastdigit*x;
        x/=2;
        ans=ans (char)('0' lastdigit);
    }
    return ans;
}
  • Related