C++ convert hex string to signed integer

前端 未结 9 2046
耶瑟儿~
耶瑟儿~ 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条回答
  •  猫巷女王i
    2020-11-22 03:22

    Try this. This solution is a bit risky. There are no checks. The string must only have hex values and the string length must match the return type size. But no need for extra headers.

    char hextob(char ch)
    {
        if (ch >= '0' && ch <= '9') return ch - '0';
        if (ch >= 'A' && ch <= 'F') return ch - 'A' + 10;
        if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10;
        return 0;
    }
    template
    T hextot(char* hex)
    {
        T value = 0;
        for (size_t i = 0; i < sizeof(T)*2; ++i)
            value |= hextob(hex[i]) << (8*sizeof(T)-4*(i+1));
        return value;
    };
    

    Usage:

    int main()
    {
        char str[4] = {'f','f','f','f'};
        std::cout << hextot(str)  << "\n";
    }
    

    Note: the length of the string must be divisible by 2

提交回复
热议问题