从第三个字节开始因此
const msg = "0F04ABABABAB";
const msg1 = "0F04ABABABAB10001FF";
function solution(msg, tags) {
const tagObj = {};
for (let i = 0; i + 3 < msg.length; ) {
const tag = parseInt(msg.slice(i, i + 2), 16);
const len = parseInt(msg.slice(i + 2, i + 4), 16);
const valueOffset = Math.floor((i + 5) / 2);
console.log(tag);
console.log(len);
console.log(valueOffset);
i = i + 3 + len * 2;
// 如果结束位置越界则报文不完整,需要舍弃
if (i >= msg.length) break;
tagObj[tag] = [len, valueOffset];
}
const res = tags.map((tag) => {
if (tagObj[tag]) {
const [len, valueOffset] = tagObj[tag];
return `${len} ${valueOffset}`;
} else {
return `0 0`;
}
});
return res.join("\n");
}
console.log(solution(msg, [15]));
/*
0F04ABABABAB
1
15
=>
4 2
0F04ABABABAB10001FF
2
15
17
=>
4 2
0 0
*/