I need to checksum a simple buffer. I decided to have a 32 bit checksum which was simply all the other 32 bit values XORed together.
I set the checksum to zero.
I xor the whole buffer together.
I place the complement of the checksum in the checksum location.
I recalculate the checksum.
I get all ones instead of zero.
In my head, any number XORed with it's complement should give zero.
It's obviously something stupid that I'm missing.
I converted it to Arduino to convince myself it wasn't hardware.
Here it is, apologies for the pointer stuff - it just made handling a byte buffer as 32 bits so much easier.
Thanks for any help.
Mike.
I set the checksum to zero.
I xor the whole buffer together.
I place the complement of the checksum in the checksum location.
I recalculate the checksum.
I get all ones instead of zero.
In my head, any number XORed with it's complement should give zero.
It's obviously something stupid that I'm missing.
I converted it to Arduino to convince myself it wasn't hardware.
Here it is, apologies for the pointer stuff - it just made handling a byte buffer as 32 bits so much easier.
Code:
uint8_t buff[56]; //buffer to hold data 32*14 = 56*8 = 448 bits
void setup() {
Serial.begin(115200);
for(uint8_t i=0;i<56;i++){ //fill with nonsense
buff[i]=i;
}
uint32_t checkSum;
uint32_t *p; //pointer to 32 bit number
p=(uint32_t*)buff+sizeof(buff)/4-1; //point to the checksum
*p=0; //zero the checksum
checkSum=calcChecksum(); //calculate with checksum=0
Serial.print("Checksum = ");
Serial.println(checkSum,HEX);
checkSum^=0xffffffff; //complement
*p=checkSum; //write to checksum location
checkSum=calcChecksum();
Serial.print("Checksum = ");
Serial.println(checkSum,HEX);
while(1){
}
}
void loop() {
}
/* CalcChecksum returns the checksum of the buffer or zero if the complement of
* the checksum is in the end 32 bits.
*/
uint32_t calcChecksum(void){
uint32_t *p; //pointer to 32 bit number
p=(uint32_t*)buff; //point to start of buffer
uint32_t tempChecksum=0; //zero checksum
for(uint8_t i=0;i<sizeof(buff)/4;i++){
tempChecksum^=*p++; //xor all words together
}
return(tempChecksum);
}
Thanks for any help.
Mike.