我正在为我的电气工程学士项目编写一个应用程序,我正在使用一个字节数组,它表示一个十六进制字符串。接收到的字节数组如下所示:
_
我的问题是如何从字节数组中获取所有的“msg”,并将它们变成一个数字?2中的“长度”字节描述了“msg”中有多少“msg”,所以我想用它来计算数组索引的数目。
var receivedBytes: [UInt8] = []
func serialDidReceiveBytes(_ bytes: [UInt8]) {
receivedBytes = bytes
print(receivedBytes)
}204、74、3、0、97、168、209、239
我想让这个变成:
var: [UInt8] = [0, 97, 168]使它像:
[0x00,0x61,0xA8]然后将这个数字变成0x61A8或小数点25000。
发布于 2019-02-26 22:10:01
给定数组:
let bytes: [UInt8] = [204, 74, 3, 0, 97, 168, 209, 239]让我们获取消息的长度:
let length = Int(bytes[2])msg是存储结果的变量:
var msg = 0index将指向整个消息的八进制索引,从LSB (bytes中的较高索引)到MSB (bytes中的较低索引)。
var index = bytes.count - 3power是我们转移八位数的力量
var power = 1然后,我们以这样的方式计算消息:
while index > 2 {
msg += Int(bytes[index]) * power
power = power << 8
index -= 1
}结果是:
print(msg) //25000或者就像@JoshCaswell建议的那样:
var msg: UInt64 = 0
var index = 3
while index < bytes.count - 2 {
msg <<= 8 //msg = msg << 8
msg += UInt64(bytes[index])
index += 1
}在这两种解决方案中,我们假设消息可以放入Int或UInt64中。
https://stackoverflow.com/questions/54894693
复制相似问题