C++ 如何以十六进制格式将数据附加到 std::string?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1255366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:20:02  来源:igfitidea点击:

How can I append data to a std::string in hex format?

c++string

提问by samoz

I have an existing std::stringand an int. I'd like to concatenate the ASCII (string literal) hexadecimal representation of the integer to the std::string.

我有一个现有的std::string和一个int. 我想将整数的 ASCII(字符串文字)十六进制表示连接到std::string.

For example:

例如

 std::string msg = "Your Id Number is: ";
 unsigned int num = 0xdeadc0de; //3735929054

Desired string:

所需的字符串

std::string output = "Your Id Number is: 0xdeadc0de";

Normally, I'd just use printf, but I can't do this with a std::string (can I?)

通常,我只会使用 printf,但我不能用 std::string 来做到这一点(我可以吗?)

Any suggestions as to how to do this?

关于如何做到这一点的任何建议?

回答by xtofl

Use a stringstream. You can use it as any other output stream, so you can equally insert std::hexinto it. Then extract it's stringstream::str()function.

使用字符串流。您可以将其用作任何其他输出流,因此您可以同样插入std::hex其中。然后提取它的stringstream::str()功能。

std::stringstream ss;
ss << "your id is " << std::hex << 0x0daffa0;
const std::string s = ss.str();

回答by Meredith L. Patterson

Building on xtofl's answer, the header you're looking for is <iomanip>. This is where std::hex, std::dec, and std::octlive, all of which can be directed into streams such that whatever gets sent into the stream after them is converted to that base.

基于 xtofl 的答案,您要查找的标题是<iomanip>. 这是 where std::hex, std::dec, 和std::octlive ,所有这些都可以被定向到流中,这样在它们被转换到那个基础之后发送到流中的任何东西。

回答by DevByStarlight

I believe 'string' only forward declares std::stringstream. So you also need to include:

我相信 'string' 只向前声明 std::stringstream。所以你还需要包括:

#include <sstream>