0

For my bluetooth communication I need a check code / checksum from a byte array. The bluetooth communication protocol says: "The instruction of check code: check code=(0 - expect the sum of byte in whole byte)"

I already got a working method in swift with the help of this post:

var checksum: UInt8 {
    let cs: Int = self.map { Int($0) }.reduce(0, +) & 0xff

    if cs >= 1 && cs <= 255 {
        return UInt8( 256 - cs )
    } else {
        return UInt8(1)
    }
}

I have to admit that I'm struggling with the whole concept of checksum from a byte array and I don't get it working in Java.

I came across the methods of the java.util.stream class but that class requires api level 24 or higher and I wanted to use 23 as minimum as it is still widely used.

Patricks
  • 715
  • 2
  • 12
  • 25

1 Answers1

0

It doesn't look very nice and smooth but I got it working:

byte checksum(byte[] buf) {
    int[] intArray = new int[buf.length];
    for(int i=0; i<buf.length; i++){
        int x = buf[i];
        intArray[i] = x;
    }

    int sum = 0;
    for (int i : intArray) {
        sum += i;
    }

    sum = sum & 0xff;

    int cs = 1;

    if (sum >= 1 && sum <= 255) {
        cs = 256 - sum;
    }

    return (byte) cs;
}
Patricks
  • 715
  • 2
  • 12
  • 25