I want to convert a hex string to a 32 bit signed integer in C++.
So, for example, I have the hex string \"fffefffe\". The binary representation of this is 111111
I had the same problem today, here's how I solved it so I could keep lexical_cast<>
typedef unsigned int uint32;
typedef signed int int32;
class uint32_from_hex // For use with boost::lexical_cast
{
uint32 value;
public:
operator uint32() const { return value; }
friend std::istream& operator>>( std::istream& in, uint32_from_hex& outValue )
{
in >> std::hex >> outValue.value;
}
};
class int32_from_hex // For use with boost::lexical_cast
{
uint32 value;
public:
operator int32() const { return static_cast( value ); }
friend std::istream& operator>>( std::istream& in, int32_from_hex& outValue )
{
in >> std::hex >> outvalue.value;
}
};
uint32 material0 = lexical_cast( "0x4ad" );
uint32 material1 = lexical_cast( "4ad" );
uint32 material2 = lexical_cast( "1197" );
int32 materialX = lexical_cast( "0xfffefffe" );
int32 materialY = lexical_cast( "fffefffe" );
// etc...
(Found this page when I was looking for a less sucky way :-)
Cheers, A.