在有索引的特定数据的情况下,使用indexedseq在scala中迭代和提取数据的最佳方法是什么
val data
=IndexedSeq(0x00,0x0F,0x33,0x35,0x35,0x35,0x36,0x35,0x30,0x37,0x31,0x33,0x30,0x38,0x31,0x30,0x33,0x43,0x4D,0x54,0x4D,0x31,0x2E,0x30,0x30,0x32)
设备发送长度为14个字节的连接命令。
00 0F 33 35 35 35 36 35 30 37 31 33 30 38 31 30 33 43 4D 54 4D 31 2E 30 30 32
页眉2字节设备ID 16字节固件版本8字节
我在下面尝试过手动检查每个索引
if(data(0)==0x00 && data(1)==0x0F){
//New Connection
val deviceId=(data.slice(2,17).map(_.toChar)).mkString
val firmwareVersion=(data.slice(18,25).map(_.toChar)).mkString
println(deviceId)
println(firmwareVersion)
}
答案 0 :(得分:1)
您可以使用模式匹配:
val data = Seq(0x00,0x0F,0x33,0x35,0x35,0x35,0x36,0x35,0x30,0x37,0x31,0x33,0x30,0x38,0x31,0x30,0x33,0x43,0x4D,0x54,0x4D,0x31,0x2E,0x30,0x30,0x32)
data match {
case 0x00::0x0F::xs =>
val deviceId=(xs.take(15).map(_.toChar)).mkString
val firmwareVersion=(data.slice(18,25).map(_.toChar)).mkString
println(deviceId)
println(firmwareVersion)
case other => // handle unexpected data
}