Hex character to int in C++

前端 未结 4 626
猫巷女王i
猫巷女王i 2021-01-14 01:20

How can I change a hex character, not string, into a numerical value?

While typing this question, I found many answers on how to convert hex strings to values. Howe

4条回答
  •  北海茫月
    2021-01-14 02:01

    Something like the following?

    //!         \return
    //!             The numeric value of ch, if it is hex, otherwise -1
    int
    fromHexChar( char ch )
    {
        static char const hexChars[] = "0123456789ABCDEF";
        char const* p = std::find( begin( hexChars ), end( hexChars ),
                                   ::tolower( (unsigned char)ch ) );
        return p == end( hexChars )
            ? -1
            : p - begin( hexChars );
    }
    

提交回复
热议问题