Swift checksum of bytes

2019-05-30 11:34发布

I have a quite tricky problem. I send an array of bytes with an iOS device to a ble device (led light) which works just fine. I have a document for all commands which is very poorly translated from chinese. The whole byte-package is build like this:

  • The front of command ( 1 byte )
  • The length of command packet ( 1 byte )
  • Command's ID ( 1 byte )
  • Command's control part ( 1 byte )
  • Data field ( 15 byte )
  • Check ( 1 byte )

For example the complete package for switching the light on is "A1080100FFFFFF59" So far everything is clear to me. The only thing I struggle with is the last byte or how it is called in the document: "Check". The document just says: "The instruction of check code: check code=(0 - expect the sum of byte in whole byte)". In the example above "59" would be the checksum. But no matter how I try to calculate it I won't get to "59".

I found the nice little helper

public extension Data {
    public func checkSum() -> Int {
        return self.map { Int($0) }.reduce(0, +) & 0xff
    } 
}

But I don't get the right "checks" for any command.

Maybe someone has an idea how this is calculated?

1条回答
Rolldiameter
2楼-- · 2019-05-30 12:08

256 - [your checksum algorithm] returns 0x59, so maybe that's it:

var data = Data([0xA1, 0x08, 0x01, 0x00, 0xFF, 0xFF, 0xFF])

extension Data {
    var checksum: Int {
        return self.map { Int($0) }.reduce(0, +) & 0xff
    }
}

let result = 256 - data.checksum
"0x\(String(result, radix: 16))" // "0x59"
查看更多
登录 后发表回答