I’ve got a problem calculating a checksum for a number of bytes (11, to be exact). Just as used in NMEA, I want to take the XOR of all those bytes and use that as the final byte. The function I’m using is:
It calculates a value, but it never seems to be correct. Does it matter if one of the bytes in the middle contains 0x00?
Any pointers would be greatly appreciated!
jensvanhoof:
I’ve got a problem calculating a checksum for a number of bytes (11, to be exact). Just as used in NMEA, I want to take the XOR of all those bytes and use that as the final byte. The function I’m using is:
for (XOR = 0, i = 0; i < strlen(string); i++) {
c = (unsigned char)string[i];
XOR ^= c;
}
It calculates a value, but it never seems to be correct. Does it matter if one of the bytes in the middle contains 0x00?
If one of the values in the middle is 0x00, then strlen will think that it is the end of the string, so any bytes after that won’t get XORed. strlen just counts bytes in the string until it gets to a 0.
If you know your strings are always 11 bytes long, try using 11 instead of strlen.
int inArray[] = {17,1,2,1,90}; // the input numbers will be a smaller or equal number than tempArray
int tempArray[]={0,0,0,0,0,0}; // only 6 here but you can have more
void setup(){
for(int i=0; i<(sizeof(inArray)/sizeof(int));i++){
tempArray[i] = inArray[i]; // fill the tempArray with values
}
int XOR = tempArray[0] ^ tempArray[1] ^ tempArray[2] ^ tempArray[3] ^ tempArray[4] ^ tempArray[5] ^ tempArray[6];
// zeros in the array not affect the result
Serial.begin(9600);
Serial.println(XOR);
}
void loop(){
}
//pejo
Moderator edit: there’s a really good reason we use CODE TAGS, and you just demonstrated it. CODE TAGS added.
What happens when you wise up and see that inArray doesn’t really need to be of int type?
The expression sizeof(inArray)/sizeof(inArray[0]) will tell you the number of bytes in the array, regardless of array type.