以十六进制或十进制打印到标准输出,一个 std::string 作为字节序列
Print to stdout, in hex or decimal, a std::string as a sequence of bytes
API 我正在使用 returns 字节序列作为 std::string。
如何将其打印到标准输出,格式为十六进制或十进制的序列。
这是我使用的代码:
int8_t i8Array[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
std::string i8InList(reinterpret_cast<const char*>(i8Array), 16);
std::string i8ReturnList;
client.GetBytes(i8ReturnList, i8InList);
cout << "GetBytes returned ";
std::copy(i8ReturnList.begin(), i8ReturnList.end(), std::ostream_iterator<int8_t>(std::cout << " " ));
我希望收到相同的输入,但顺序相反。然而这段代码打印的是:
GetBytes returned ☺☻♥♦♣
♫☼
注意:字节序列是任意字节序列,它不是书面语言的表示。
流会将这些字节解释为字符,当控制台获取这些字符时,它将显示编码规定它应该显示的任何内容。
使用例如int
作为 std::ostream_iterator
模板参数而不是将它们打印为数字。
您可能希望将存储在 std::string
中的 char
转换为 int
,因此 std::cout
不会将它们打印为字符,但就像纯整数。
要以十六进制打印它们,请使用 std::hex
,如以下可编译代码片段 (live on Ideone) 所示:
#include <iostream>
#include <string>
using namespace std;
inline unsigned int to_uint(char ch)
{
// EDIT: multi-cast fix as per David Hammen's comment
return static_cast<unsigned int>(static_cast<unsigned char>(ch));
}
int main()
{
string data{"Hello"};
cout << hex;
for (char ch : data)
{
cout << "0x" << to_uint(ch) << ' ';
}
}
输出:
0x48 0x65 0x6c 0x6c 0x6f
API 我正在使用 returns 字节序列作为 std::string。
如何将其打印到标准输出,格式为十六进制或十进制的序列。
这是我使用的代码:
int8_t i8Array[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
std::string i8InList(reinterpret_cast<const char*>(i8Array), 16);
std::string i8ReturnList;
client.GetBytes(i8ReturnList, i8InList);
cout << "GetBytes returned ";
std::copy(i8ReturnList.begin(), i8ReturnList.end(), std::ostream_iterator<int8_t>(std::cout << " " ));
我希望收到相同的输入,但顺序相反。然而这段代码打印的是:
GetBytes returned ☺☻♥♦♣
♫☼
注意:字节序列是任意字节序列,它不是书面语言的表示。
流会将这些字节解释为字符,当控制台获取这些字符时,它将显示编码规定它应该显示的任何内容。
使用例如int
作为 std::ostream_iterator
模板参数而不是将它们打印为数字。
您可能希望将存储在 std::string
中的 char
转换为 int
,因此 std::cout
不会将它们打印为字符,但就像纯整数。
要以十六进制打印它们,请使用 std::hex
,如以下可编译代码片段 (live on Ideone) 所示:
#include <iostream>
#include <string>
using namespace std;
inline unsigned int to_uint(char ch)
{
// EDIT: multi-cast fix as per David Hammen's comment
return static_cast<unsigned int>(static_cast<unsigned char>(ch));
}
int main()
{
string data{"Hello"};
cout << hex;
for (char ch : data)
{
cout << "0x" << to_uint(ch) << ' ';
}
}
输出:
0x48 0x65 0x6c 0x6c 0x6f