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

3
  • depending on the compiler you are using, you should have some option to specify how structure members are packed, have a look here stackoverflow.com/questions/4306186/… Commented Apr 26, 2014 at 5: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. Commented Apr 26, 2014 at 7:48
  • lookup serialization. That's what you need. Commented Apr 26, 2014 at 9:38

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.