Calculating checksum of a structure
Hi! I need to know, how to calculate the checksum of this structure:
Code:
struct stepdata { George |
Hi George.
You can explicitly cast one pointer to another of different type by doing something like this and use the new pointer to process whatever that is in there. char *ptr=(char *)&data; Unfortunately in your example it will run into some problem because the stepdata structure is not well-aligned. GCC will pad bytes to make 32bit int's and struct boundary aligned to 32bit unless you ask it not to do so with __attribute__((packed)). See http://www.delorie.com/djgpp/v2faq/faq22_11.html for more details about sizeof struct and extra paddings. Code:
#include <stdio.h> linux~$ ./checksum Dump data (15): 01 02 03 04 00 05 00 06 00 07 08 00 00 00 00 Calculated checksum: 24 Dump data (15): 01 02 03 04 00 05 00 06 00 07 08 00 00 00 24 |
One more bit of info about your packing problem, if you choose to force byte packing of that structure you will get a "Bus Fault" if you compile and run your software on any processor other than Intel X86 because the 16 and 32 bit integers will not be word aligned. For example, it will crash on a Sparc.
i.e... struct stepdata data={1,2,3,4,5,6,7,8,0}; **bus fault** But it will work on Intel. |
In x86 it can get away from crashes, but with performance penalty. To avoid this you should
1) manually pad extra bytes so that int16 words and int32 dwords are 16bit and 32bit aligned respectively, or 2) define dedicated function to perform the checksum over this particular structure type The following one is an attempt to A) align int16 and int32 variables., and B) keep struct size multiple of 32bit. (If you don't do B, once you have an array of this struct, the 2nd one may have everything mis-aligned.) Code:
struct stepdata { |
All times are GMT -5. The time now is 07:51 AM. |