The following will do, with function Append4ByteInteger
doing the actual work:
#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;
}
You can check that the stream actually contains 0x00 0x00 0x00 0x01
using a hex dump utility (e.g. hexdump
).
Note that the function assumes that the integer has a value of 0 or greater. If you want to ensure that, you may want to use an unsigned int
instead, or probably even a uint32_t
, as the size of an int is platform-dependent.