如何在 C++ 中使用 std::stringstream 解析十六进制字符串

此函数将任何十六进制字符串如 55 转换为其等效的十进制值:

hex_to_dec.cpp
#include <sstream>
#include <int>

unsigned int hexToDec(const std::string& str) {
    unsigned int ret;
    std::stringstream ss;
    ss << std::hex << str;
    ss >> ret;
    return ret;
}

例如

hex_usage_example.cpp
hexToDec("55"); // 返回 85

注意虽然代码有些简洁,但它可能既不是最高效也不是最简洁的选项,特别是对于不太了解 std::stringstream 的开发者。


Check out similar posts by category: C/C++