简体   繁体   中英

How to convert a large integer from a string to a uint64_t?

I have a large integer stored as a string. I need to convert it into an integer ( uint64_t ). I tried stoi() , but it is crashing after throwing an instance of std::out_of_range .

The string has maximum of 64-bit integer value, max value of 18,446,744,073,709,551,615 (maximum for an unsigned long int).

How do I do this, other than (of course) manually?

As long as the string contains a number that is less than std::numeric_limits<uint64_t>::max() , then std::stoull() will do what you're expecting.

(The std::stoull() function is new in C++11.)

You can use stringstream to do this. This is supported in C++98 (the std::stoull() function was added in C++11).

#include <stdint.h>
#include <iostream>
#include <sstream>
using namespace std;

uint64_t string_to_uint64(string str) {
  stringstream stream(str);
  uint64_t result;
  stream >> result;
  return result;
}

int main() {
  string str = "1234567891234567";
  uint64_t val = string_to_uint64(str);
  cout << val;
  return 0;
}

One approach could be to use stringstreams:

unsigned long long val;
std::istringstream stream(inputstring);
stream >> val;

According to this reference there's at least an overload for operator>> for unsigned long long , which could be the same as uint64_t .

Otherwise you'll probably have to do it manually, eg split the string into handleable pieces, and join the results by multiplication with the right base.


To be sure I'd go with this for now:

unit64_t to_uint64(std::string const & in) {
  static_assert(sizeof(unsigned long long) == sizeof(uint64_t), "ull not large enough");
  unsigned long long val = 0;
  std::istringstream stream(in);
  stream >> val;
  return val;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM