1

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

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115
user2605241
  • 21
  • 1
  • 3
  • depending on the compiler you are using, you should have some option to specify how structure members are packed, have a look here http://stackoverflow.com/questions/4306186/structure-padding-and-structure-packing – Felice Pollano Apr 26 '14 at 05:54
  • The portable way is to do a lossless conversion of the values into a byte stream (although handling the `double` is a bit problematic). A semi-portable way would be to replace `bool flag` with `uint32_t flag`, `bool flagArray[32]` with `char flagArray[32]` or even `uint32_t flagArray`; use `htonl`, and check that sizeof(struct myData) is the sum of the size of the elements. – M.M Apr 26 '14 at 07:48
  • lookup serialization. That's what you need. – bolov Apr 26 '14 at 09:38

1 Answers1

2

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.

little_birdie
  • 5,600
  • 3
  • 23
  • 28