【问题标题】:Convert stringized hex character to std::string将字符串化的十六进制字符转换为 std::string
【发布时间】:2012-03-25 12:56:42
【问题描述】:

我有以下几点:

char const* code = "3D";

我需要将这个 2 位词法十六进制转换为 std::string,这将是一个长度为 1 的字符串(不包括空终止符)。我也可以使用 boost 库。我该怎么做?

在上面的示例中,我应该有一个 std::string 如果正确转换,则打印“=”。

【问题讨论】:

标签: c++ string boost


【解决方案1】:

我认为这个订单上的某些东西应该可以工作:

std::istringstream buffer("3D");
int x;

buffer >> std::hex >> x;
std::string result(1, (char)x);

std::cout << result;  // should print "="

【讨论】:

    【解决方案2】:

    例如,仅使用标准 C++03:

    #include <cstdlib>
    #include <string>
    #include <iostream>
    
    int main() {
      char const* code = "3D";
      std::string str(1, static_cast<char>(std::strtoul(code, 0, 16)));
      std::cout << str << std::endl;
    }
    

    在实际应用中,您必须测试整个字符串是否已被转换(strtoul 的第二个参数)以及转换结果是否在允许的范围内。


    这是一个更详细的示例,使用 C++11 和 Boost:

    #include <string>
    #include <cstddef>
    #include <iostream>
    #include <stdexcept>
    
    #include <boost/numeric/conversion/cast.hpp>
    
    template<typename T>
    T parse_int(const std::string& str, int base) {
      std::size_t index = 0;
      unsigned long result = std::stoul(str, &index, base);
      if (index != str.length()) throw std::invalid_argument("Invalid argument");
      return boost::numeric_cast<T>(result);
    }
    
    int main() {
      char const* code = "3D";
      std::string str(1, parse_int<char>(code, 16));
      std::cout << str << std::endl;
    }
    

    【讨论】:

      【解决方案3】:

      在 Boost 1.50 版(将于今年 5 月发布)中,您只需编写

      string s;
      boost::algorithm::unhex ( code, std::back_inserter (s));
      

      适用于 std::string、std::wstring、QtString、CString 等。

      【讨论】:

        【解决方案4】:

        它不是 C++,但您仍然可以使用旧的 scanf:

        int d;
        scanf("%x", &d);
        

        或者从使用sscanf的字符串:

        int d;
        sscanf(code, "%x", &d);
        

        并使用std::string

        int d;
        sscanf(code.c_str(), "%x", &d);
        

        在某些情况下,C 格式函数(scanf 和 printf 系列)比面向对象的等效函数更易于使用。

        【讨论】:

        • 你不应该提供一个sscanf 的例子吗?
        • scanf 是邪恶的,应该避免。
        • @Geoffroy:也许是一个适用于std::string 的例子?你知道,那使用c_str
        • @Bukes 为什么它是邪恶的?如果你知道如何处理它,它工作得很好!而且不同的是写的更短。
        • @Geoffroy - 出于多种原因,它是邪恶的。它根本不处理格式错误的输入,您无法识别这一点。许多其他人比我同意的更杰出- scanf 是邪恶的。 c-faq.com/stdio/scanfprobs.html, stackoverflow.com/questions/456303/…
        猜你喜欢
        • 2012-11-09
        • 2018-01-31
        • 1970-01-01
        • 1970-01-01
        • 2013-02-07
        • 1970-01-01
        • 2018-01-26
        • 2014-12-04
        • 1970-01-01
        相关资源
        最近更新 更多