0

I try understand BSD checksum calulcation algorithm, writed in Java language.

Wiki writed:

byte checksum(byte[] input) {
byte checksum = 0;
for (byte cur_byte: input) {
    checksum = (byte) (((checksum & 0xFF) >>> 1) + ((checksum & 0x1) << 7)); // Rotate the accumulator
checksum = (byte) ((checksum + cur_byte) & 0xFF);                        // Add the next chunk
}
return checksum; 

}

And my questions:

  1. Why we use bitwise & in this line checksum = (byte) ((checksum + cur_byte) & 0xFF); ? 0xFF is binary "11111111" and this operation not return always this same number?
  2. What is a sense of this operation? checksum = (byte) (((checksum & 0xFF) >>> 1) + ((checksum & 0x1) << 7)); I understand binary operation and logical and arithmetical shifts, but dont understand what we doing.

Thanks for help :)

wukkie
  • 127
  • 1
  • 2
  • 12

1 Answers1

0
  1. b & 0xFF is often used to cast signed byte to bit-identical int. In this case it is unnecessary - (byte)(b & 0xFF) identical to (b). For example ((byte)-1) & 0xFF = 255

  2. 12345678 >>>1   01234567
    12345678  <<7    80000000 ADD -> 81234567

Thus it is cyclic rotation

Sergey Alaev
  • 3,851
  • 2
  • 20
  • 35