c++ - 如何在 C++ 中正确地将字符串转换为十六进制
问题描述
我想std::string
使用操纵器将 a 转换为 C++ 中的十六进制,std::hex
但我无法让它正常工作。
这是我到目前为止写的:
#include <iostream>
#include <sstream>
int main() {
std::string a = "hello world";
std::stringstream ss;
for(size_t i = 0; i < a.length(); i++) { // Print one character at the time
ss << std::hex << (int)a[i];
std::cout << ss.str() << " ";
ss.str(std::string());
}
return 0;
}
使用 hexdump 的相同字符串的输出是6568 6c6c 206f 6f77 6c72 0a64
之前的代码打印类似:6865 6c6c 6f20 776f 726c 64
,所以我怀疑这与平台的字节序有关。我的问题是:如何在不弄乱字节序的情况下转换字符串?