Reputation: 792
I'm trying to calculate the checksum in an NMEA sentence, but i can't get the correct value. Here is my test code.
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)
This returns a checksum of 40, not the 28 i'd expected.
What am i doing wrong?
Upvotes: 1
Views: 838
Reputation: 17572
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
Upvotes: 4