如何将 int 写入 stringstream?
How do I write an int to a stringstream?
我有 std::stringstream
1 个字节:
std::stringstream message;
message.write((const char[]) {0x55}, 1);
std::string res(message.str());
如何附加 int a = 1;
(4 个字节)?
我想获取存储在 message
的底层 std::string
:
中的值
0x55 0x00 0x00 0x00 0x01
我为字节序列的工作选择了正确的工具?
"How append int a = 1;
(4 bytes)?"
就是这样:
uint32_t a = 1; // Use uint32_t to be sure to have 4 bytes.
message.write((const char*)&a, sizeof(a));
正如您提到的 "specific socket protocol",您可能需要使用 htonl()
函数处理网络字节顺序:
uint32_t a = htonl(1);
下面会做,函数 Append4ByteInteger
做实际工作:
#include <iostream>
#include <sstream>
#include <string>
static std::stringstream& Append4ByteInteger (std::stringstream& stream, int value) {
auto v = static_cast<uint32_t>(value);
stream << static_cast<unsigned char>(v >> 24);
stream << static_cast<unsigned char>(v >> 16);
stream << static_cast<unsigned char>(v >> 8);
stream << static_cast<unsigned char>(v);
return stream;
}
int main () {
std::stringstream message;
message.write((const char[]) {0x55}, 1);
Append4ByteInteger(message, 1);
std::cout << "result: '" << message.str() << "'" << std::endl;
}
您可以使用十六进制转储实用程序(例如 hexdump
)检查流是否实际包含 0x00 0x00 0x00 0x01
。
请注意,该函数假定整数的值为 0 或更大。如果你想确保这一点,你可能想使用 unsigned int
代替,甚至可能 uint32_t
,因为 int 的大小是平台相关的。
写入 int
可能会因内部字节顺序、大端、小端或其他顺序而异。
从逻辑上屏蔽每个字节,然后将每个无符号字符放入流中会更便携
您将需要在接收端重建 int
,再次使用 shift
等逻辑操作
您也可能不需要所有 4 个字节,因此您可以轻松地发送 3 个字节。
如果你打算做二进制流,你应该查看移位和掩码并理解它们。
我有 std::stringstream
1 个字节:
std::stringstream message;
message.write((const char[]) {0x55}, 1);
std::string res(message.str());
如何附加 int a = 1;
(4 个字节)?
我想获取存储在 message
的底层 std::string
:
0x55 0x00 0x00 0x00 0x01
我为字节序列的工作选择了正确的工具?
"How append
int a = 1;
(4 bytes)?"
就是这样:
uint32_t a = 1; // Use uint32_t to be sure to have 4 bytes.
message.write((const char*)&a, sizeof(a));
正如您提到的 "specific socket protocol",您可能需要使用 htonl()
函数处理网络字节顺序:
uint32_t a = htonl(1);
下面会做,函数 Append4ByteInteger
做实际工作:
#include <iostream>
#include <sstream>
#include <string>
static std::stringstream& Append4ByteInteger (std::stringstream& stream, int value) {
auto v = static_cast<uint32_t>(value);
stream << static_cast<unsigned char>(v >> 24);
stream << static_cast<unsigned char>(v >> 16);
stream << static_cast<unsigned char>(v >> 8);
stream << static_cast<unsigned char>(v);
return stream;
}
int main () {
std::stringstream message;
message.write((const char[]) {0x55}, 1);
Append4ByteInteger(message, 1);
std::cout << "result: '" << message.str() << "'" << std::endl;
}
您可以使用十六进制转储实用程序(例如 hexdump
)检查流是否实际包含 0x00 0x00 0x00 0x01
。
请注意,该函数假定整数的值为 0 或更大。如果你想确保这一点,你可能想使用 unsigned int
代替,甚至可能 uint32_t
,因为 int 的大小是平台相关的。
写入 int
可能会因内部字节顺序、大端、小端或其他顺序而异。
从逻辑上屏蔽每个字节,然后将每个无符号字符放入流中会更便携
您将需要在接收端重建 int
,再次使用 shift
您也可能不需要所有 4 个字节,因此您可以轻松地发送 3 个字节。
如果你打算做二进制流,你应该查看移位和掩码并理解它们。