当前位置:   article > 正文

JS ArrayBuffer 类型转换及拼接_js arraybuffer 拼接

js arraybuffer 拼接

1 转换

1 字符串转为ArrayBuffer
// 字符串转为ArrayBuffer对象,参数为字符串
const str2ab = function(str) {
  var buf = new ArrayBuffer(str.length * 2); // 每个字符占用2个字节
  var bufView = new Uint16Array(buf);
  for (var i = 0, strLen = str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
2.ArrayBuffer转字符串
// ArrayBuffer转为字符串,参数为ArrayBuffer对象, 字符串编码为一个字节
const ab2str = function (buf) {
  return String.fromCharCode.apply(null, new Uint8Array(buf));
}

// ArrayBuffer转为字符串,参数为ArrayBuffer对象字符串编码为js默认编码
const ab2strU16 = function (buf) {
  return String.fromCharCode.apply(null, new Uint16Array(buf));
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
3.ArrayBuffer与十六进制的互相转换
/**
 * 十六进制转 bytearray
 */
var hex2ab = function(hex){
  var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
    return parseInt(h, 16)
  }))

  var buffer = typedArray.buffer
  return buffer
}

 // ArrayBuffer转16进度字符串示例
const ab2hex = function (buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

2拼接

function concatenate(resultConstructor, ...arrays) {
    let totalLength = 0;
    for (let arr of arrays) {
        totalLength += arr.length;
    }
    let result = new resultConstructor(totalLength);
    let offset = 0;
    for (let arr of arrays) {
        result.set(arr, offset);
        offset += arr.length;
    }
    return result;
}
使用:
totalmsg = concatenate(Uint8Array, totalmsg, submsg)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

更多内容

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/145174
推荐阅读
相关标签
  

闽ICP备14008679号