字节的快速校验和 [英] Swift checksum of bytes
问题描述
我有一个非常棘手的问题.我使用iOS设备将字节数组发送到ble设备(led灯),该设备工作正常. 我有所有命令的文档,但是中文翻译很少. 整个字节包的构建如下:
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:
- 命令开头(1个字节)
- 命令包的长度(1个字节)
- 命令的ID(1个字节)
- 命令的控制部分(1个字节)
- 数据字段(15个字节)
- 检查(1个字节)
例如,用于打开照明灯的完整包装是"A1080100FFFFFF59" 到目前为止,一切对我来说都是清楚的.我唯一要解决的是最后一个字节或它在文档中的调用方式:检查" . 该文件只是说:校验码的指令:校验码=(0-期望整个字节的总和)" . 在上面的示例中,"59" 是校验和.但是无论我如何计算,我都不会到达"59" .
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?
推荐答案
256 - [your checksum algorithm]
返回0x59
,也许就是这样:
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"
这篇关于字节的快速校验和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!