01-20-2012 11:41 AM
I am trying to calculate the 16bit arithmetic sum of a structure data type to obtain checksum of data header of a data packet.
structure is defines as follows:
I am having trouble with 8bit data types. How can i concatnate those to get 16bit words to add them up? Also with 8bit array needs to be calculated with 16bit words at time.
any help will be appreciated.
01-21-2012 10:20 AM
An option is to create an uint16-pointer that points to the address of your structure variable. With sizeof you can ask how many bytes the structure has. Subsequent you use the uint16-pointer to add the values from all the words (or bytes) in your structure.
However there is one minor risk: packing. The data of subsequent fields in your structure are (default) only sequential bytes if any new type starts at an N-byte boundary (http://en.wikipedia.org/wiki/Data_structure_alignment). You can pack data more dense - using pragma pack - but this also applies when writing binary files of building libraries for others. I think that your structure ik ok. Myself, I always insert some reserves (for future use) and try to start all types at an 8-byte boundary. Especially with large data packets, a few extra bytes in the header is minor overhead.