Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C Programming > Re: Checksum in a struct

Reply
Thread Tools

Re: Checksum in a struct

 
 
Peter Nilsson
Guest
Posts: n/a
 
      07-13-2012
On Jul 12, 12:56*am, pozz <(E-Mail Removed)> wrote:
> I have a function that computes a 16-bit checksum (following whatever
> algorithm) of a memory space:
>
> * *unsigned int checksum(const void *buffer, size_t size);


If this is doing a byte-wise checksum then this has potential problems
for any type with
padding, not just struct. Even unpadded types where values can have
multiple representations
(e.g. negative zero) has problems.

> I want to embed this checksum in a struct:
>
> * *struct PStruct {
> * * *int x;
> * * *unsigned int y;
> * * *char z[13];
> * * *...
> * * *unsigned int checksum;
> * *};
>
> How to use the checksum() function above? *I propose:
>
> * *struct PStruct ps;
> * *...
> * *ps.checksum = checksum(&ps, offsetof(struct PStruct, checksum));
>
> Is there a better mechanism?


Change your checksum function to a cumulative one...

unsigned checksum(unsigned old, unsigned data);

[User wider type as needed.]

Then apply as...

ps.checksum = 0;
ps.checksum = checksum(ps.checksum, ps.x);
ps.checksum = checksum(ps.checksum, ps.y);
for (int i = 0; i < 13; i++)
ps.checksum = checksum(ps.checksum, ps.z[i]);
...

--
Peter
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: Checksum in a struct Stefan Ram C Programming 2 07-25-2012 12:13 PM
Re: Checksum in a struct Eric Sosman C Programming 12 07-21-2012 06:44 PM
Re: Checksum in a struct fmassei@gmail.com C Programming 0 07-11-2012 04:39 PM
Can *common* struct-members of 2 different struct-types, that are thesame for the first common members, be accessed via pointer cast to either struct-type? John Reye C Programming 28 05-08-2012 12:24 AM
struct my_struct *p = (struct my_struct *)malloc(sizeof(struct my_struct)); Chris Fogelklou C Programming 36 04-20-2004 08:27 AM



Advertisments