簡體   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