Reputation:
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?
Upvotes: 3
Views: 3486
Reputation: 223689
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];
}
Upvotes: 2