C++ convert hex string to signed integer

前端 未结 9 2020
耶瑟儿~
耶瑟儿~ 2020-11-22 03:08

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

9条回答
  •  庸人自扰
    2020-11-22 03:12

    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.

提交回复
热议问题