C Board  

Go Back   C Board > General Programming Boards > C Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 02-20-2009, 09:37 AM   #1
Registered User
 
Join Date: Jan 2009
Posts: 151
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];
}
Subsonics is offline   Reply With Quote
Old 02-20-2009, 09:41 AM   #2
Kernel hacker
 
Join Date: Jul 2007
Location: Farncombe, Surrey, England
Posts: 15,686
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.
matsp is offline   Reply With Quote
Old 02-20-2009, 09:54 AM   #3
Registered User
 
Join Date: Jan 2009
Posts: 151
Perfect, Thank you.
Subsonics is offline   Reply With Quote
Old 02-20-2009, 12:54 PM   #4
Algorithm Dissector
 
iMalc's Avatar
 
Join Date: Dec 2005
Location: New Zealand
Posts: 2,476
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
iMalc is offline   Reply With Quote
Old 02-20-2009, 01:19 PM   #5
Registered User
 
Join Date: Jan 2009
Posts: 151
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. :-)
Subsonics is offline   Reply With Quote
Reply

Thread Tools
Display Modes

Forum Jump

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


All times are GMT -6. The time now is 05:28 AM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.0 RC2

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22