1
votes

Hi guys I'm trying to calculate the checksum of a struct that I've made. I created a struct packet that contains multiple char and int variables. Is there a way to calculate the checksum of such a struct?

My first guess was, calculating the packet size and then use a cycle to calculate for each position its value, sum those together and then return that value.

The problem is that I don't know how to calculate each position of this packet, since there are multiple type of variable cause it's a struct.

Do you have any suggestion?

1
Yes, there is a way. Take into account each of the fields individually. The question as it stands now is somewhat broad, you should edit and add some relevant code, especially the prototype of your checksum calculating function would be useful.Jabberwocky
The type of members in the struct is not important. A checksum should not care about this. But your struct might have padding bytes that are not used and will not be initialized etc. You should skip those.Gerhardh
If you want identity checking, you'll have to add some hashing to account for permutations of identical values in different fields. Otherwise, a "Big Dog" string field will be equal to a "Dig Bog" field if you use a strictly accumulative summation.Mark Benningfield

1 Answers

1
votes

What you need here is to access each byte of the struct. You can do that by taking its address, casting it to unsigned char *, assigning the address to a variable of that type, then using the variable to loop through the bytes:

unsigned int sum = 0;
unsigned char *p = (unsigned char *)&mystruct;
for (int i=0; i<sizeof(mystruct); i++) {
    sum += p[i];
}

Note however that if your struct contains any padding that the values of the padding bytes are unspecified, so that can mess with your checksum. If that's the case, then you'll need to do the above for each field in the struct individually.

For example:

unsigned int sum = 0;
unsigned char *p = (unsigned char *)&mystruct.field1;
for (int i=0; i<sizeof(mystruct.field1); i++) {
    sum += p[i];
}
p = (unsigned char *)&mystruct.field2;
for (int i=0; i<sizeof(mystruct.field2); i++) {
    sum += p[i];
}