I'm transferring data over network, so trying to set up a header, where first 3 bytes are a message type, and the next 4 bytes are the size of the message. When I'm adding an integer, for anything over 127 bytes, I'm overflowing. How do I set up such header?
Here's a simple example. If num is 127 or less, then the output is correct, but if it's 128 or more, then the output is all messed up.
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
string bytesAsStr(char* src, int size)
{
stringstream ss;
ss << std::hex;
for (int i = 0; i < size; i++)
{
ss << std::setw(2) << std::setfill('0') << (int)src[i] << " ";
}
return ss.str();
}
int main()
{
// 3 chars + 1 int
const int size = 3 + sizeof(int);
char x[size];
memcpy(x, "lsa", 3);
int num = 129;
memcpy(x + 3, &num, sizeof(int));
cout << bytesAsStr(x, size) << endl;
int out = *(x + 3);
cout << "out: " << out << endl;
}
*(x + 3)is of typechar. Are you trying to read aintout of that? In that case, usememcpyto copy those bytes into aintvalue.