Swift checksum of bytes

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”.

  • Swift: Unable to downcast AnyObject to SKPhysicsBody
  • Passing array through segue in swift
  • Wrong information displayed on SecondViewController when table row clicked
  • how to loop through elements of array of <UnsafeMutablePointer> in Swift
  • How to check if an element is in an array
  • Convert bytes/Uint8 array to Int in Swift
  • 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?

    Solutions Collect From Internet About “Swift checksum of bytes”

    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"