module.exports = {
  string2ListInt: string2ListInt,
  int2Hex: int2Hex,
  buf2hex: buf2hex,
  buf2string: buf2string,
  changeArrayByValue: changeArrayByValue,
  removeWrongArray: removeWrongArray,
}

///string转换List<int>
function string2ListInt(str) {
  let utf8 = [];
  for (let i = 0; i < str.length; i++) {
    let charcode = str.charCodeAt(i);
    if (charcode < 0x80) {
      utf8.push(charcode);
    } else if (charcode < 0x800) {
      utf8.push(0xc0 | (charcode >> 6),
        0x80 | (charcode & 0x3f));
    } else if (charcode < 0xd800 || charcode >= 0xe000) {
      utf8.push(0xe0 | (charcode >> 12),
        0x80 | ((charcode >> 6) & 0x3f),
        0x80 | (charcode & 0x3f));
    } else { // surrogate pair
      i++;
      charcode = 0x10000 + (((charcode & 0x3ff) << 10) | (str.charCodeAt(i) & 0x3ff));
      utf8.push(0xf0 | (charcode >> 18),
        0x80 | ((charcode >> 12) & 0x3f),
        0x80 | ((charcode >> 6) & 0x3f),
        0x80 | (charcode & 0x3f));
    }
  }
  return utf8; // 在小程序中，这个数组可以替代 Uint8Array 使用
}

///10进制转16进制
function int2Hex(num) {
  // 将数字转换为16进制字符串
  let hexStr = num.toString(16);
  // 将16进制字符串转换回数字（这一步在微信小程序中通常不需要，除非有特殊需求）
  let i = parseInt(hexStr, 16);
  return i;
}

///获取数据
function buf2hex(buffer) {
  return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
}

///数据转文字
function buf2string(buffer) {
  var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
  var str = ''
  for (var i = 0; i < arr.length; i++) {
    str += String.fromCharCode(arr[i])
  }
  return str
}

/// value 数组转换的根据值  array 需要转换的数组 
/// 根据数组中的一个值分隔数组， 分割后组成的新数组
function changeArrayByValue(value, array) {
  // var value = "IMU data";
  var newArray = new Array();
  var dataStr = '';
  for (var i = 0; i < array.length; i++) {
    if (array[i] == value) {
      if (dataStr) {
        //把分隔的数据添加新到数组中
        newArray.push(dataStr.substring(0, dataStr.length - 2).split("  "));
      }
      dataStr = '';
      continue;
    } else {
      dataStr += (array[i] + "  ");
      //把最后分隔的数据添加新到数组中
      if (i == array.length - 1) {
        newArray.push(dataStr.substring(0, dataStr.length - 2).split("  "));
      }
    }
  }
  return newArray;
}

///数组 去除数组中长度不等于三的属性
function removeWrongArray(array) {
  for (var i = 0; i < array.length; i++) {
    if (array[i].length != 9) {
      array.splice(i, 1);
      removeWrongArray(array);
    }
  }
  return array;
}