I'm trying to write a reusable message object that would take its properties, convert them into a delimited string (using 0x1d
group seperator), put that in a char
buffer, and also be able to do the reverse (from char
back to object).
This reason why I must do this is that I am completely limited by the OS capabilities to only send messages that are of type char
and a fixed size, so this is my wrapper for that.
Here is what I have so far. Easy to pack.. now, how can I write a sensible way to unpack it. I am OK if every child of this class must manually unpack this data, but I just don't see how. I tried getline
but then I end up with a string and will have to write many conversion functions.. There must be a simpler way.
Note I am in C++98.
#include <iostream>
#include <sstream>
#include <string.h>
class Msg {
public:
Msg(){
delim = 0x1d;
}
int8_t ia;
int16_t ib;
int32_t ic;
int64_t id;
uint8_t ua;
uint16_t ub;
uint32_t uc;
uint64_t ud;
std::string str = "aaa bbb ccc dddd";
char sz[64];
char delim;
// convert to a char buffer
void ToBuffer(unsigned char* b, int s){
std::stringstream ss;
ss << ia << delim
<< ib << delim
<< ic << delim
<< id << delim
<< ua << delim
<< ub << delim
<< uc << delim
<< ud << delim
<< str << delim
<< sz << delim;
strncpy((char*)b, ss.str().c_str(), s);
b[s-1] = '\0';
}
// convert from a char buffer
void FromBuffer(unsigned char* b, int s){
// what on earth to do here..
// could use getline which returns a string after
// each delimiter, then convert each string to the
// value in a known order.. but at that point I may
// as well have written this all in C... !
}
void Print(){
std::cout
<< " ia " << ia
<< " ib " << ib
<< " ic " << ic
<< " id " << id
<< " ua " << ua
<< " ub " << ub
<< " uc " << uc
<< " ud " << ud
<< " str " << str
<< " sz " << sz;
}
};
int main()
{
Msg msg;
msg.ia = 0xFE;
msg.ib = 0xFEFE;
msg.ic = 0xFEFEFEFE;
msg.id = 0xFEFEFEFEFEFEFEFE;
msg.ua = 0xEE;
msg.ub = 0xDEAD;
msg.uc = 0xDEADBEEF;
msg.ud = 0xDEADBEEFDEADBEEF;
snprintf(msg.sz, 64, "this is a test");
msg.Print();
int s = 128;
unsigned char b[s];
msg.ToBuffer(b, s);
Msg msg2;
msg2.FromBuffer(b, s);
//msg2.Print();
return 0;
}