How do I write an int to a stringstream?

4.2k Views Asked by At

I have std::stringstream with 1 byte:

std::stringstream message;
message.write((const char[]) {0x55}, 1);
std::string res(message.str());

How append int a = 1; (4 bytes)?

I want to get as values stored in the message's underlying std::string:

0x55 0x00 0x00 0x00 0x01

And right tool I chose for the job with the sequence of bytes?

3

There are 3 best solutions below

0
On BEST ANSWER

"How append int a = 1; (4 bytes)?"

Simply like that:

uint32_t a = 1; // Use uint32_t to be sure to have 4 bytes.
message.write((const char*)&a, sizeof(a));

As you mention "specific socket protocol", you'll probably need to take care of the network byte order using the htonl() function:

uint32_t a = htonl(1);
2
On

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.

0
On

Writing an int might differ based on internal byte order, big endian, little endian, or others.

It would be more portable to mask off each byte logically, and then put each unsigned char into the stream

You will need to rebuild the int on the recieving side, again using logical operations like shift

It is also likely you will not need all 4 bytes, so you could easily just send 3 for example.

You should look up shifting and masking and understand them if you plan to do binary streams.