Velocity Reviews - Computer Hardware Reviews

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

Reply
Thread Tools

Re: Checksum in a struct

 
 
jadill33@gmail.com
Guest
Posts: n/a
 
      07-12-2012
On Wednesday, July 11, 2012 10:56:53 AM UTC-4, 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);
>
> 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?


Pack the structure by writing all the bytes of each individual member to a byte array. This will avoid the compiler padding for alignment issue. If needed, use the ntoh family of functions to put the necessary 2 and 4 byte words in big-endian before checksum if the need to support architectures with different endians arise.

\code
#define member_sizeof( type, member ) sizeof ( ((type*)0)->member )
size_t pack_PStruct_size( void )
{
return member_sizeof (struct PStruct, x) +
member_sizeof (struct PStruct, y) +
member_sizeof (struct PStruct, z) +
... ;
}
\endcode

You can use 'mempcpy' to simplify packing an array.

\code
void* mempcpy( void* dst, const void* src, size_t n )
{
return (unsigned char*)memcpy( dst, src, n ) + n;
}

void pack_PStruct( unsigned char* packed_array, struct PStruct* ps )
{
unsigned char* p = packed_array;

p = mempcpy( p, ps->x, member_sizeof( struct PStruct, x ) );
p = mempcpy( p, ps->y, member_sizeof( struct PStruct, y ) );
p = mempcpy( p, ps->z, member_sizeof( struct PStruct, z ) );
...
}
\endcode

Be wary of uninitialized characters in 'z' if you checksum all 13 characters in the array.

You can tweak the interface as needed.

Best regards,
John D.
 
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