Packing multiple variable into one string
A stream of chars are sent out to a communication devic开发者_C百科e. For readability purposes, i wrote inidividual configurations as variables:
unsigned char a1;
unsigned char a2;
unsigned char a3;
unsigned char a4;
unsigned char a5;
std::string a6;
unsigned char a7;
unsigned char a8;
What is the best way to pack it into a variable tightly so that it's aligned perfectly?
Till now I've think of put everything into a struct
.
edit: struct
doesn't look like a viable option since struct
doesn't hold string
, and string is varying in size, although is a one time declared thing. Compiled in GCC
edit2: Gonna go with packed struct
method, but will convert the string
to a c_str
first. Until a better answer, this is the way to be.
A packed structure, rather than just a structure would be more appropriate.
EDIT: Ofcourse, you should not use string
as a part of your structure, It skipped me while answering but as others have pointed out. You should conver string
to character array using str.c_str());
and then store the same in the packed structure.
struct foo {
unsigned char a1;
unsigned char a2;
unsigned char a3;
unsigned char a4;
unsigned char a5;
.
.
.
} __attribute__((packed));
GCC specific. Read: http://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html#Variable-Attributes Also have a look at the aligned
variable attribute
Or manually insert dummy variables to fillup the places where the compiler may introduce padding.
You really want to send std::string to device? string has no fixed size. you should use a6.c_str(), and send all with an array of unsigned char and it's size?
A simple array of unsigned char
should be enough. But struct
is the better way though.
Btw, I don't think you can use std::string
in the struct
. You need array of unsigned char
there.
I'm not sure if this is your request but you can use std::ostringstream class to merge all the variables in a single string:
std::ostringstream sOutStream;
sOutStream << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
std::string sOutput = sOutStream.str();
If you want to send an object like a std::string
you'll need to use some sort of serialization and/or protocol. The 'raw' string object will contain typically contain a pointer to the actual string data - and that pointer will be meaningless on the other end of the link. Not mention that the data the pointer points to won't be sent (without some sort of serialization) and that some sort of protocol will be necessary to deal with the variable length data that a std::string
represents.
I think you may have more to consider than just packing things tightly.
精彩评论