-1

I have byte array and I need get checksum:

let bytes : [UInt8] = [0xC4, 0x03, 0x01, 0x09, 0x03]

I try this code but it did not help me:

let result = 256 - dataByte.checksum
extension Data {
 var checksum: Int {
    return self.map { Int($0) }.reduce(0, +) & 0xff
 }
}

My friend who is the developer try to get checksum on Kotlin, like this:

var checksum = 0
    for (i in 0..lastIndex) {
        checksum = checksum xor this[i].toInt()
    }
    return checksum

And he got this result 0x0B and I need the same result only on swift 4.

1 Answers1

1

This is how you XOR all the values in your array:

let bytes: [UInt8] = [0xC4, 0x03, 0x01, 0x09, 0x03]
let checksum = bytes.reduce(0, ^)
print(checksum) // 204, which equals 0xCC

As mentioned by Martin R, the result is 0xCC, and not 0x0B.

pckill
  • 3,709
  • 36
  • 48
  • 1
    There's no need for `& 0xFF` in this case. In the original code, that was to mask off the overflow from `+`, but using `^` the output cannot be larger than the input. – Rob Napier Feb 26 '19 at 18:43