how convert std::string unsigned integer, , allowing long inputs?
for example, input of 5000000000 should return 705032704 (5000000000 mod 2^32), assuming here unsigned 32 bits. input of 9999999999999999999999999999 should return 268435455.
std::stoi , friends give std::out_of_range when such large number provided.
using std::istringstream::operator>>(unsigned) fails given such input.
is there function convert string integer, without bailing out in case of large inputs? (i'd prefer avoid writing 1 myself if possible.)
you can write 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; } this works because unsigned overflow works modulo arithmetic in c++.
from 3.9.1/4
unsigned integers, declared unsigned, shall obey laws of arithmetic modulo 2^n n number of bits in value representation of particular size of integer
Comments
Post a Comment