繁体   English   中英

将字符串化十六进制字符转换为std :: string

[英]Convert stringized hex character to std::string

我有以下内容:

char const* code = "3D";

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

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

我觉得这个命令应该有用:

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

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

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

例如,仅使用标准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;
}

它不是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系列)比面向对象的等效函数更容易使用。

在Boost版本1.50(即今年5月份)中,您只需编写

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM