Offset is outside the bounds of the DataView

前言

在做微信小程序开发,向蓝牙发送信息时,遇到这样一个错误 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))

回答: 报错信息"IndexOutOfRangeException: Index was outside the bounds of the array."表示数组索引超出了数组的边界。这个异常通常发生在使用计数器作为数组索引时,计数器出错导致索引越界。\[1\]这并不是.Net的Bug,而是由于代码中的错误导致的异常。解决这个问题的方法是检查代码中的计数器是否正确,并确保在使用计数器作为数组索引时不会超出数组的边界。\[2\]在这种情况下,可能需要检查模型文件中的维度参数是否正确设置。\[2\]另外,也可以通过分析使用的onnx文件来解决这个问题。\[2\]根据报错邮件的内容,这个异常集中在某个方法中,可能需要仔细检查这个方法的代码,确保计数器的使用没有问题。\[3\] #### 引用[.reference_title] - *1* *3* [.Net多线程陷阱---Dictionary Index was outside the bounds of the array.](https://blog.csdn.net/ZF_TIAN_XIA/article/details/125916489)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [Yolov5Net报错【已解决】:System.IndexOutOfRangeException: ‘Index was outside the bounds of the array.](https://blog.csdn.net/Zythonista/article/details/125594047)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

An_s

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值