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

3

使用stringstream很容易将字符串进行十六进制编码,但是是否可能使用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;
}

我不打算直接位移字节或使用旧的 C 函数,例如 scanf 函数族。
2个回答

5

我认为您还需要在每对数字后添加0x。 - Maciej Stachowski
@MaciejStachowski 不需要在 std::stoi 中使用前缀。 - Some programmer dude

1

如果您在数字之间放置某种分隔符,它就会有关联。举个例子,让我们先更改您的代码,在输出的每个字节之间插入一个空格:

#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;
}

接下来,让我们写一个小程序从cin读取数据,并再次将其打印为字符:

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

int main()
{
    int i;
    while (std::cin >> std::hex >> i)
        std::cout << static_cast<char>(i);
    return 0;
}

当我将第一个管道传递给第二个时,输出为hello, world
显然,从stringstream读取数据与从std::cin读取数据大致相同--我使用cin来演示,同时几乎不改变您的代码。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接