将 ASCII std::string 转换为十六进制
有没有一种简单的方法可以将 ASCII std::string 转换为 HEX?我不想将其转换为数字,我只想将每个 ASCII 字符转换为其十六进制值。输出格式也应该是 std::string。 即:“TEST”将是“0x54 0x45 0x53 0x54”或某种类似的格式。
我找到了这个解决方案,但也许有更好的解决方案(没有字符串到整数到字符串的转换):
std::string teststring = "TEST";
std::stringstream hValStr;
for (std::size_t i=0; i < teststring.length(); i++)
{
int hValInt = (char)teststring[i];
hValStr << "0x" << std::hex << hValInt << " ";
}
谢谢,
/mspoerr
is there an easy way to convert an ASCII std::string to HEX? I don't want to convert it to a number, I only want to convert each ASCII character to it's HEX value. The output format should also be a std::string.
i.e.: "TEST" would be "0x54 0x45 0x53 0x54" or some similar format.
I found this solution, but maybe there is a better one (without string to int to string conversion):
std::string teststring = "TEST";
std::stringstream hValStr;
for (std::size_t i=0; i < teststring.length(); i++)
{
int hValInt = (char)teststring[i];
hValStr << "0x" << std::hex << hValInt << " ";
}
Thanks,
/mspoerr
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您不关心 0x,那么使用 std::copy 很容易做到:
If you don't care about the 0x it's easy to do using
std::copy
:此答案到另一个我想,问题就是你想要的。您必须添加一个
" "
作为ostream_iterator
的分隔符参数才能获取字符之间的空格。This answer to another question does what you want, I think. You'd have to add a
" "
as separator argument for theostream_iterator
to get whitespaces between the characters.