Ok. By the looks of things you're sending this data to hardware for processing. I didn't realise that.
In this case you could use a struct as you were planning to. It's quite common practice. You will probably have to tell the compiler not to pad out the struct, but I see in another thread you are already aware of that. If you are only targeting a single platform/compiler and don't have endianness worries, then you could do it this way. All you need to do is reinterpret_cast the struct into an unsigned char* (or whatever type your send function takes). eg:
#pragma pack(push, 1)
struct MyStruct
{
unsigned char c;
unsigned int i;
};
#pragma pack(pop)
void send(unsigned char* buf, size_t length)
{
// send buf
}
int main()
{
MyStruct myObj;
myObj.c = 'A';
myObj.i = 1;
send(reinterpret_cast<unsigned char*>(&myObj), sizeof(myObj));
return 0;
}
#pragma pack(push, 1)
struct MyStruct
{
unsigned char c;
unsigned int i;
};
#pragma pack(pop)
void send(unsigned char* buf, size_t length)
{
// send buf
}
int main()
{
MyStruct myObj;
myObj.c = 'A';
myObj.i = 1;
send(reinterpret_cast<unsigned char*>(&myObj), sizeof(myObj));
return 0;
}
To copy to clipboard, switch view to plain text mode
My personal preference is to write portable code. So I would only do it this way if performance absolutely demanded it. Instead I would probably detect the endianness of the host at runtime, construct an unsigned char array of the correct size, reinterpret_cast the array at the appropriate offsets to copy in the appropriate values - applying endian conversions if necessary. But to each their own.
Edit: I notice Qt provides qFromBigEndian to handle all the endian conversion stuff.
Bookmarks