Search code examples
c++type-conversionunsigned

C++ integer from string


How do you convert a std::string to an unsigned integer, and allowing very long inputs?

For example, an input of 5000000000 should return 705032704 (5000000000 mod 2^32), assuming here that unsigned is 32 bits. An input of 9999999999999999999999999999 should return 268435455.

std::stoi and friends give an std::out_of_range when such a large number is provided.

Using std::istringstream::operator>>(unsigned) simply fails given such input.

Is there any function to convert a string to an integer, without bailing out in the case of large inputs? (I'd prefer to avoid writing one myself if possible.)


Solution

  • You can write a function yourself:

    unsigned int get_uint(const std::string &s) {
        unsigned int r = 0U;
        for(auto c : s) {
            assert(std::isdigit(c));
            r = r * 10 + (c - '0');
        }
        return r;
    }
    

    Live example

    This works because unsigned overflow works as modulo arithmetic in C++.

    From 3.9.1/4

    Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2^n where n is the number of bits in the value representation of that particular size of integer