Thread: Making of checksum using XOR

  1. #1
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485

    Making of checksum using XOR

    I´m trying to make a checksum of the content in a datapacket struct and want to make sure I get it right. Let´s say that the struct have three variables where on is an array like this:

    Code:
    typedef struct {
       char a;
       char b;
       char c[10];
    } DataPacket;
    Should I then make the checksum like this?

    Code:
    char checksum;
    
    checksum = a ^ b;
    
    for(i = 0; i < sizeof(c); i++){
       checksum ^= c[i];
    }

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Yes, you can. And it will be a slightly "better" checksum than using addition, because all bits have an equal chance of being detected as erroneous. But you can only detect an odd-number of failures for each bit.

    An addition checksum fails to detect a double failure of the upper-most bit [assuming the checksum is equal size to the transmission unit, e.g. 1 byte checksum].

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    Perfect, Thank you.

  4. #4
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    That's called an LRC.
    In practice, both checksum and LRC are inferrior to a good CRC.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  5. #5
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    Aah, I see. I´m trying to comunicate with a device that uses checksum so I´m stuck with that.
    The docs I have says "checksum (exclusive OR of above 124 bytes)" I just wanted to make sure that my approach would work or I would be stuck re-sending the first packet. :-)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. checksum sender vs reciever?
    By silhoutte75 in forum C Programming
    Replies: 1
    Last Post: 04-13-2008, 01:27 PM
  2. weird checksum function
    By sagitt13 in forum C Programming
    Replies: 7
    Last Post: 10-31-2006, 01:25 AM
  3. Help figuring out a checksum algorithm
    By barem23 in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 01-11-2003, 04:24 AM
  4. Reading Binary file to find Checksum
    By Abbila in forum C++ Programming
    Replies: 0
    Last Post: 09-25-2002, 09:52 PM