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.
0x55 0x00 0x00 0x00 0x01? Are you sure you want to treat it as a byte buffer instead of a textual string? Just asking to make surestd::stringis notstd::stringstream, finding out how to usestd::stringstreamis easy, and your syntax is made-up. Which book are you using?std::string? The code you've shown is not valid C++, it's using C's compound literals which your compiler allows as an extension.