What does "int & = 0xFF" do in the checksum?

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];
        }

        //What does this line actually do?
        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?

+4
source share
4 answers

You seem to understand the situation well.

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?

.

, 32- , 8- ?

.

+4

, .

checksum &= 0xFF;

:

checksum = checksum & 0xFF;

, , 0xFF int:

checksum = checksum & 0x000000FF;

3 ( ).

: 32- , 8- , , 8- , .

+7

(8- ), . & = 0xFF, , 8LSB 32- ( int), 0 255.

8 - , . , .

, , 32 , 8- .

+3

, 8 &= 0xFF. 8 , - 0.

Reducing the checksum to 8 bits reduces reliability. Think of two 32-bit checksums that are different from each other, but the least significant 8 bits are equal. In the case of truncation to 8 bits, both will be equal, in the 32-bit case this is not so.

+3
source

Source: https://habr.com/ru/post/1696067/


All Articles