Reputation: 21
I am trying to convert a struct consisting of the following:
struct myData
{
double value1;
int32_t value2;
bool flag;
int32_t value3;
int32_t value4;
bool flagArray[32];
}
I wanted to convert this struct into an unsigned char array so that I can apply CRC from an open source (http://www.netrino.com/code/crc.zip). However I noticed that the bool var will be automatically typecast into a var with 4 bytes (in which 3 bytes are undefined). Hence, the CRC checksum may fails if it is received and interpreted differently from the sender.
May I know is there any way that I can resolve this problem?
Thanks
Upvotes: 1
Views: 473
Reputation: 5857
Ok, you have a couple of problems.
The first is that, from the way you word your question, it seems you are trying to send a C structure over a network connection. That's a really bad idea, because the exact memory layout of your C structure is dependent on the system, processor type, compiler, compiler flags.. etc. For example, one processor could be 32 bit, the other 64. One could be big-endian, the other little-endian. This would cause the structures to not match.
The reason that you are seeing three extra bytes after the bool is because you are dealing with an 8 bit bool type and the processor is 32 bits. On a 32 bit architecture, most compilers will align structures on a 32 bit boundary.. which leaves the 'space' of three unused bytes in the structure that you are seeing.
Some compilers offer an option to force packing of a structure.. on gcc it is #pragma pack. This will eliminate your extra space. But it doesn't solve your endian-ness problem. For that, you need to use the functions htonl/ntohl, htons/ntohs etc.
Look up the man pages for these and for #pragma pack in the compiler docs.
Upvotes: 2