使用字符串流解码十六进制编码的字符串

goj*_*oji 2 c++ encoding hex stringstream

使用字符串流对字符串进行十六进制编码很容易,但是可以反向并使用字符串流解码生成的字符串吗?

#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>

int main()
{
  std::string test = "hello, world";

  std::stringstream ss; 
  ss << std::hex << std::setfill('0');
  for (unsigned ch : test)
    ss << std::setw(2) << int(ch);

  std::cout << ss.str() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

我不打算直接移位字节或使用旧的c函数,例如scanf系列函数.

Som*_*ude 5

如果您只有一个没有分隔符的十六进制数字流,那就不那么容易了.您可以一次使用std::basic_istream::getstd::basic_istream::read提取两个数字,然后使用eg std::stoi转换为一个整数,然后可以将其类型转换为a char.