Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for negative values when using lexical_cast to unsigned type

Tags:

c++

boost

I have a situation where I am grabbing command line arguments and using boost::lexical_cast<unsigned long>(my_param). I was hoping that negative values of my_param would cause lexical_cast to throw, but instead it happily converts them, with -1 becoming 18446744073709551615. Which seems absurd, as the max value for an unsigned long is 2^32-1, it looks much more like an unsigned long long.

So I am looking for either a smarter way to cast the char * input to unsigned long, or a way to verify that I have not accepted a negative value in its disguise as a large unsigned long long.

like image 421
rlong Avatar asked Nov 02 '12 16:11

rlong


Video Answer


1 Answers

There is a bug report against boost with your problem which explains why it behaves that way:

boost::lexical_cast has the behavior of stringstream, which uses num_get functions of std::locale to convert numbers. If we look at the [22.2.2.1.2] of Programming languages — C++ ( or at [22.2.2.1.2] Working Draft, Standard for Programming Language C++) we`ll see, that num_get uses the rules of scanf for conversions. And in the C99 standard for %u the input value minus sign is optional, so if a negative number is read, no errors will arise and the result will be the two's complement.

And also a suggested wrapper workaround:

https://svn.boost.org/trac/boost/ticket/5494

like image 129
Frederick Roth Avatar answered Sep 30 '22 05:09

Frederick Roth