Swift 3 xor校验和计算

Swift 3 xor checksum calculation

我正在尝试计算 NMEA 语句中的校验和,但无法获得正确的值。这是我的测试代码。

import UIKit

//$GPGLL,5300.97914,N,00259.98174,E,125926,A*28

let str = "GPGLL,5300.97914,N,00259.98174,E,125926,A"


var xor: UInt8 = 0
for i in 0..<str.characters.count {
    xor = xor ^ Array(str.utf8)[i]
}

print(xor)

这个 returns 校验和为 40,而不是我预期的 28。

我做错了什么?

The checksum is simple, just an XOR of all the bytes between the $ and the * (not including the delimiters themselves), and written in hexadecimal.

let str = "$GPGLL,5300.97914,N,00259.98174,E,125926,A*"

var xor: UInt8 = 0
for i in 1..<(str.characters.count - 1){
    xor = xor ^ Array(str.utf8)[i]
}
extension UnsignedInteger {
    var hex: String {
        var str = String(self, radix: 16, uppercase: true)
        while str.characters.count < 2 * MemoryLayout<Self>.size {
            str.insert("0", at: str.startIndex)
        }
        return str
    }
}

let strWithCheckSum = str + xor.hex
print(strWithCheckSum) // GPGLL,5300.97914,N,00259.98174,E,125926,A*28