ArrayBufferUtil.js 2.2 KB
export default class ArrayBufferUtil {
  static ab2str(buf) {
    return String.fromCharCode.apply(null, new Uint16Array(buf));
  }

  static str2ab(str) {
    let buf = new ArrayBuffer(str.length * 2); // one char use 2 byte
    let bufView = new Uint16Array(buf);
    for (let i = 0, strLen = str.length; i < strLen; i++) {
      bufView[i] = str.charCodeAt(i);
    }
    return buf;
  }

  static strToUint8Array(str) {
    let out, i, len, c;
    out = "";
    len = str.length;
    let uintArray = [];
    for (i = 0; i < len; i++) {
      c = str.charCodeAt(i);
      if ((c >= 0x0001) && (c <= 0x007F)) {
        uintArray.push(c);
      } else if (c > 0x07FF) {
        uintArray.push(0xE0 | ((c >> 12) & 0x0F));
        uintArray.push(0x80 | ((c >> 6) & 0x3F));
        uintArray.push(0x80 | ((c >> 0) & 0x3F));
        //out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
        //out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
        //out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
      } else {
        uintArray.push(0xC0 | ((c >> 6) & 0x1F));
        uintArray.push(0x80 | ((c >> 0) & 0x3F));
        //out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
        //out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
      }
    }
    return new Uint8Array(uintArray);
  }

  static uint8ArrayToStr(uint8, index) {
    let out, i, len, c;
    let char2, char3;
    out = "";
    len = uint8.buffer.byteLength;
    i = uint8.offset + index; //pzm update 前两个字符乱码
    while (i < uint8.limit) {
      c = uint8.view[i++];
      switch (c >> 4) {
      case 0:
      case 1:
      case 2:
      case 3:
      case 4:
      case 5:
      case 6:
      case 7:
        // 0xxxxxxx
        out += String.fromCharCode(uint8.view[i - 1]);
        break;
      case 12:
      case 13:
        // 110x xxxx 10xx xxxx
        char2 = uint8.view[i++];
        out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
        break;
      case 14:
        // 1110 xxxx 10xx xxxx 10xx xxxx
        char2 = uint8.view[i++];
        char3 = uint8.view[i++];
        out += String.fromCharCode(((c & 0x0F) << 12) |
          ((char2 & 0x3F) << 6) |
          ((char3 & 0x3F) << 0));
        break;
      }
    }
    return out;
  }
}