how to convert a big int to a double in C++

101 Views Asked by At

In C++, I want to get the square root of a big int. The number is less than the maximum integer represented as a double, so this approach should work. The ttmath library doesn't have a square root function.

I'm using the ttmath library for big ints.

I wrote the following program:

#include <ttmath/ttmath.h>
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    ttmath::UInt<4>  a = "234567890123456789012345";

    // convert BigInt to double
    double d=(double)a;

    // then take the square root of the double
    double b = sqrt(d);

    cout << b << endl;
}

Compiling it results in the following error the following error:

cannot convert 'ttmath::UInt<3>' to 'double' without a conversion operator
    double d=(double)a;

So it doesn't like using a cast for converting to a double.

What is the required conversion operator?

1

There are 1 best solutions below

0
Jan Schultke On

The ttmath library doesn't directly allow converting Int or UInt to double. You need to go through ttmath::Big

ttmath::UInt<4> a = "234567890123456789012345";

// 12 (signed) exponent bits, 52 mantissa bits;
// that's all we need for converting to double precision, assuming binary64 representation
ttmath::Big<12, 52> big = a;
double d = big.ToDouble();

That being said, you don't need to convert to double to compute the square root or print.

ttmath::Big<12, 52> big = a;
big.Sqrt();
std::cout << big;

You can also compute the integer square root with a.Sqrt(), but this wouldn't give you any fractional digits.