Link to home
Start Free TrialLog in
Avatar of erimay
erimay

asked on

Checksum code in C

Dear experts,

        I need to add a checksum to a frame that will be sent from client A to Client B thru protocol. Could someone please show me an example of checksum code to add a checksum to a frame before it is send, on client A side, and calculating the checksum for error detection on the receiver side (client B)?

Please reply asap.
Thank you.
SOLUTION
Avatar of sunnycoder
sunnycoder
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of void_main
void_main

Or you download the quake II source code from www.idsoftware.com and have a look into crc.c and crc.h. There is networking code for client/server too, but only if you download the full sourcecode (not the "game source")
I think that could help!
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Well. the example i've posted is not really using bytes, but half-bytes (nibbles). but you can easily modify it to bytes, words, whatever you want (and can XOR it).
S.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Kdo forgot to advance the pointer in the buffer...

Here's the corrected code:

/*
  ChecksumRegion -- Calculate a checksum over a memory region
    Buffer - Start address of region to checksum
    Length - Number of bytes to checksum
*/

int ChecksumRegion (void *Buffer, int Length)
{
  unsigned char *Ptr;
  int   idx;
  int   XORValue;
  int   SUMValue;

  Ptr = (unsigned char *)Buffer;
  XORValue = 0;
  SUMValue = 0;
  for (idx = 1; idx <= Length; ++idx, Ptr++)
  {
    XORValue ^= *Ptr;
    SUMValue += (*Ptr * idx);
  }
  return (XORValue ^ SumValue);
}