C++ convert hex string to signed integer

前端 未结 9 1993
耶瑟儿~
耶瑟儿~ 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:25

    Andy Buchanan, as far as sticking to C++ goes, I liked yours, but I have a few mods:

    template 
    struct HexTo {
        ElemT value;
        operator ElemT() const {return value;}
        friend std::istream& operator>>(std::istream& in, HexTo& out) {
            in >> std::hex >> out.value;
            return in;
        }
    };
    

    Used like

    uint32_t value = boost::lexical_cast >("0x2a");
    

    That way you don't need one impl per int type.

提交回复
热议问题