|
Boost Users : |
Subject: Re: [Boost-users] boost::lexical_cast<> with hex strings?
From: boost_at_[hidden]
Date: 2010-07-15 16:11:43
-----Original Message-----
From: boost-users-bounces_at_[hidden]
[mailto:boost-users-bounces_at_[hidden]] On Behalf Of anony
Sent: Thursday, July 15, 2010 1:09 AM
To: boost-users_at_[hidden]
Subject: [Boost-users] boost::lexical_cast<> with hex strings?
I'd like to do something like:
boost::uint16_t b(std::lexical_cast<boost::uint16_t>("xa"));
I have no control of the string stream that lexical_cast uses
internally, so how could I implement this?
P.S.: There are a lot of false statements made about this functionality
on the web, some people claim that boost::lexical_cast<> can do the
conversion out of the box, but this is not so in my tests.
What about doing this
struct hexint
{
operator unsigned int()
{
return value;
}
unsigned int value;
};
inline std::istream &operator>>(std::istream &in, hexint &rhs)
{
std::ios::fmtflags flags=in.flags();
in.unsetf(std::ios::oct);
in.unsetf(std::ios::dec);
in.unsetf(std::ios::hex);
unsigned int temp=0;
in >> temp;
in.setf(flags);
if(in.bad())
{
throw boost::bad_lexical_cast();
}
rhs.value=temp;
return in;
}
//Then you can do
hexint x=boost::lexical_cast<hexint>("0x2a");
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net