前言
在做微信小程序开发,向蓝牙发送信息时,遇到这样一个错误 Offset is outside the bounds of the DataView
开始
hexStringToArrayBuffer(str) {
console.log('开始咋转化' + str)
var count = str.length / 2;
console.log(count)
let buffer = new ArrayBuffer(count);
let dataView = new DataView(buffer);
for (var i = 0; i < count; i++) {
var curCharCode = parseInt(str.substr(i * 2, 2), 16);
dataView.setUint8(i, curCharCode);
}
return buffer;
}
let data = "31940000000000000000119400041960000"
console.log(hexStringToArrayBuffer(data))
问题出现
注意!count长度为17.5,导致去创建ArrayBuffer数组的时候出现问题。也就是协议指令长度不够除2
解决方法
1.需要协议指令自行补充长度,count必须是整数
2.前端创建ArrayBuffer的时候四舍五入,如下
hexStringToArrayBuffer(str) {
console.log('开始咋转化'+str)
var count = str.length / 2;
console.log(count)
if (count.toString().indexOf('.') != -1) {
count = parseInt(count) + 1 // 有.5就加 1
count = parseInt(count) // 或者不加
}
console.log(count)
let buffer = new ArrayBuffer(count);
let dataView = new DataView(buffer);
for (var i = 0; i < count; i++) {
var curCharCode = parseInt(str.substr(i * 2, 2), 16);
dataView.setUint8(i, curCharCode);
}
return buffer;
}
let data = "31940000000000000000119400041960000"
console.log(hexStringToArrayBuffer(data))