Re: Checksum in a struct

Discussion in 'C Programming' started by Peter Nilsson, Jul 13, 2012.

  1. On Jul 12, 12:56 am, pozz <> 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);
    ...

    --
    Peter
     
    Peter Nilsson, Jul 13, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Eric Sosman

    Re: Checksum in a struct

    Eric Sosman, Jul 11, 2012, in forum: C Programming
    Replies:
    12
    Views:
    642
    Tim Rentsch
    Jul 21, 2012
  2. Stefan Ram

    Re: Checksum in a struct

    Stefan Ram, Jul 11, 2012, in forum: C Programming
    Replies:
    2
    Views:
    371
    James Kuyper
    Jul 25, 2012
  3. Re: Checksum in a struct

    , Jul 11, 2012, in forum: C Programming
    Replies:
    0
    Views:
    341
  4. Re: Checksum in a struct

    , Jul 12, 2012, in forum: C Programming
    Replies:
    0
    Views:
    376
  5. Tim Rentsch

    Re: Checksum in a struct

    Tim Rentsch, Jul 21, 2012, in forum: C Programming
    Replies:
    0
    Views:
    338
    Tim Rentsch
    Jul 21, 2012
Loading...

Share This Page