Why is there no std::stou?

后端 未结 3 1252
时光取名叫无心
时光取名叫无心 2020-12-10 00:31

C++11 added some new string conversion functions:

http://en.cppreference.com/w/cpp/string/basic_string/stoul

It includes stoi (string to int), stol (string t

3条回答
  •  孤城傲影
    2020-12-10 01:00

    unsigned long ulval = std::stoul(buf);
    unsigned long mask = ~0xffffffffl;
    unsigned int uival;
    if( (ulval & mask) == 0 )
        uival = (unsigned int)ulval;
    else {
        ...range error...
    }
    

    Using masks to do this with the expected value size in bits expressed in the mask, will make this work for 64-bit longs vs 32-bit ints, but also for 32-bit longs vs 32-bit ints.

    In the case of 64-bit longs, ~0xffffffffl will become 0xffffffff00000000 and will thus see if any of the top 32 bits are set. With 32-bit longs, it ~0xffffffffl becomes 0x00000000 and the mask check will always be zero.

提交回复
热议问题