我正在尝试将字符串的字节转换为十六进制格式。
基于此答案(以及许多其他一致的答案),我尝试了代码:
#include <sstream>
#include <iomanip>
#include <iostream>
int main ()
{
std::string inputText = u8"A7°";
std::stringstream ss;
// print every char of the string as hex on 2 values
for (unsigned int i = 0; i < inputText.size (); ++i)
{
ss << std::hex << std::setfill ('0') << std::setw (2) << (int) inputText[i];
}
std::cout << ss.str() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
但是某些字符以UTF 8编码则无法正常工作。
对于Instance,在包含以UTF8编码的度数符号(°)的字符串中,结果为:ffffffc2ffffffb0而不是c2b0。
现在,我希望算法可以对单个字节起作用,而不管它们的内容如何,而且结果似乎忽略了该setw(2)参数。
为什么会得到这样的结果?
(在此处运行测试程序)