I've been struggling with some low-level messaging for quite some time and it turned out to be an issue with the checksum calculation. I thought the bitwise XOR operator didn't care about sign, so I was using a QByteArray
to store the bytes, and using the at
method, that returns a char
, to calculate the checksum. The messages were properly acknowledged sometimes, but not always.
Looks like the guys on the other end were using uint8_t
to store the bytes, and
the checksum was failing in some situations. I solved it by casting the char
to uint8_t
, but I'm seriously baffled about that.
Why does the bitwise XOR operator care about sign? I thought it worked on a bit-level, regardless of what they represented. Here's a piece of code I've used to try to understand it.
#include <stdio.h>
#include <stdint.h>
#include <iostream>
#include <bitset>
int main ()
{
uint8_t a = 0b10010101;
char b = 0b10010101;
uint32_t checksum;
checksum = 55;
checksum ^= a;
std::cout << std::bitset<32>(checksum) << std::endl;
checksum = 55;
checksum ^= b;
std::cout << std::bitset<32>(checksum) << std::endl;
}
Even tho both integers hold the same bits, the operation yields different results in each case.