微信小程序中对于蓝牙通讯数据处理常用的工具函数

一、十六进制转字符串

export const hexToStr = function(hex, encoding) {
	var trimedStr = hex.trim();
	var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
	var len = rawStr.length;

	var curCharCode;
	var resultStr = [];
	for (var i = 0; i < len; i = i + 2) {
		curCharCode = parseInt(rawStr.substr(i, 2), 16);
		resultStr.push(curCharCode);
	}
	var val = "";
	var arr = resultStr;
	for (let i = 0; i < arr.length; i++) {
		val += String.fromCharCode(arr[i]);
	}
	return val;
}

二、十进制转16进制

export const tenToHex = (num, digit = 4) => {
	const hex = num.toString(16);
	return hex.padStart(digit, 0);
}

三、字符串转16进制

export const stringToHex = (str) =>{
	var val = "";
	for (var i = 0; i < str.length; i++) {
		if (val == "") {
			val = str.charCodeAt(i).toString(16); //获取字符的Unicode码然后转16进制
		} else {
			val += str.charCodeAt(i).toString(16); //获取字符的Unicode码然后转16进制再拼接,中间用逗号隔开
		}
	}
	return val;
}

四、arrayBuffer转16进制字符串

export const arrayBufferToHexString = (buffer) => {
	const hexArr = Array.prototype.map.call(
		new Uint8Array(buffer),
		function(bit) {
			return ('00' + bit.toString(16)).slice(-2)
		}
	)
	return hexArr.join('').toUpperCase();
}

五、十六进制字符串转ArrayBuffer

export let hexStringToArrayBuffer = (str) => {
	//十六进制转ArrayBuffer
	return new Uint8Array(str.match(/[\da-f]{2}/gi).map(function(h) {
		return parseInt(h, 16)
	})).buffer
}

六、十六进制转GB2312

npm install iconv-lite

 export let hexToGb2312 = (hexString)=> {
  const buffer = Buffer.from(hexString, 'hex');
  const decodedString = iconv.decode(buffer, 'GB2312');
  return decodedString;
}

你可能感兴趣的:(微信小程序,notepad++,小程序)