I implemented this checksum algorithm that I found, and it works fine, but I can’t figure out what this "& = 0xFF" line does.
I looked bit by bit and the operator, and wikipedia claims that it is logical And all the bits in with B. I also read that 0xFF is equivalent to 255, which should mean that all bits are equal to 1. If you accept any number and 0xFF, will not is it a number id? So, A and 0xFF gives A, right?
So, I thought, wait a minute, the checksum in the code below is a 32-bit Int, but 0xFF is 8 bits. Does this mean that the result of the checksum & = 0xFF is that 24 bits end with zeros and only the remaining 8 bits are saved? In this case, the checksum is truncated to 8 bits. Is this what is going on here?
private int CalculateChecksum(byte[] dataToCalculate)
{
int checksum = 0;
for(int i = 0; i < dataToCalculate.Length; i++)
{
checksum += dataToCalculate[i];
}
checksum &= 0xff;
return checksum;
}
Also, if the result is truncated to 8 bits, is that because 32 bits is pointless in the checksum? Is it possible to have a situation where a 32-bit checksum catches corrupted data when an 8-bit checksum does not have?
James source
share