Krin Yongvongphaiboon
Krin Yongvongphaiboon

Reputation: 85

Large numbers from string to int in c++

I did some search before I ask this question. I tried using unsigned int then use strtoul to convert from string to unsigned int. Even simple code like

 unsigned int num = 99999999999999999999999999999999999999999999999999999999999999999999999999999999

This code still not working. I want to be able to do something like this:

     unsigned int num = 99999999999999999999999999999999999999999999999999999999999999999999999999999999;
     unsigned int num2 = 1;
     unsigned int ans = num + num2;

I want to be able to do something like this:

 string num1 = "99999999999999999999999999999999999999999999999999999999999999999999999999999999;"
 string num2 = "1"
 string conv_ans;

 unsigned int conv1 = strtoul(num1); 
 unsigned int conv2 = strtoul(num2); 
 unsigned int ans = conv1 + conv2;

 conv_ans = ans;

Thank you!

Upvotes: 0

Views: 3453

Answers (3)

thatmagicalcat
thatmagicalcat

Reputation: 11

Use these set of functions according to your needs

  stoi(num1);   // to int
  stol(num1);   // to long
  stoll(num1);  // to long long
  stoul(num1);  // to unsigned long
  stoull(num1); // to unsigned long long

Upvotes: 0

vsoftco
vsoftco

Reputation: 56547

As mentioned in @Drew's answer, there is no C++ built-in type that can store integers as large as you want. A quick and easy to use multi-precision library comes with Boost and it's called Boost.Multiprecision. It is reasonably fast, and writing code that uses it is a breeze (no need for precompiled headers or other shared libraries, just -I /path/to/boost). For example, computing factorial(1000) (which is a really big number) looks like

#include <boost/multiprecision/cpp_int.hpp>
#include <iostream>

int main()
{
   using namespace boost::multiprecision;

   cpp_int u = 1; // multi-precision integer
   for(int i = 1; i < 1000; ++i) // compute 1000!
      u *= i;

   std::cout << u << std::endl; // prints 1000!
}

One advantage of Boost.Multiprecision is that it is very well integrated with the C++ stream libraries, and you can basically use it as a built in type. The library has also support for floating point numbers, rationals etc (see the documentation).

Furthermore, Boost is one of the most "standardized" C++ libraries (many features of Boost ended up in C++11), and it is highly used, so you may give it a try.

Upvotes: 2

Drew Dormann
Drew Dormann

Reputation: 63765

I want to be able to do something like this

You can't.

unsigned int cannot store values greater than std::numeric_limits<unsigned int>::max(). Often that's around 4 billion.

To store and manage integers of arbitrary size, such as the number of atoms in the Milky Way (roughly your number), you will need to use a "big int" library, such as GMP.

Upvotes: 3

Related Questions