最近做小程序蓝牙连接手表的项目,用作解析数据和拼装数据
/**
* 16进制字符串转10进制数字 hex2int('12') => 18
*/
function hex2int(hex) {
return parseInt(hex, 16)
}
/**
* 10进制字符串转16进制字符串 int2hex(18) => '12'
*/
function int2hex(int, len) {
if (len) {
return (int).toString(16).toUpperCase().padStart(len, "0")
} else {
return (int).toString(16).toUpperCase()
}
}
/**
* 16进制字符串转 ArrayBuffer
*/
function hexToArrayBuffer(hex) {
let hexArr = hex
if (typeof hex === 'string') {
hexArr = hex.match(/[\da-f]{2}/gi)
}
return new Uint8Array(
hexArr.map((byte) => {
return parseInt(byte, 16);
})
).buffer;
};
/**
* ArrayBuffer转16进制字符串
*/
function arrayBufferToHex(buffer) {
let hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function (bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('');
}
/**
* hex字符串转数组
* s为要转换的字符串 num为转换为几个一起的数
*'0102'类型转换为['0x11','0x02']
*/
function stringHexToArrayHex(s, num = 2, t = '0x') {
let re = new RegExp(".{" + num + "}", "g");
let a = [];
let n;
while ((n = re.exec(s)) != null) {
a[a.length] = t + n[0];
}
return a;
}
/**
* hex数组转hex进制字符串
*/
function arrayHexToStringHex(arr) {
return arr.map(s => s.slice(2)).toString().replace(/,/g, '');
}
/**
* ASCII码转16进制 strToHexCharCode
*/
function asciiToHex(str) {
let hexCharCode = '';
for (let i = 0; i < str.length; i++) {
hexCharCode += (str.charCodeAt(i)).toString(16)
}
return hexCharCode.toLocaleUpperCase()
}
/**
* 16进制转ASCII码 hexCharCodeToStr
*/
function hexToAscii(hexCharCodeStr) {
let trimedStr = hexCharCodeStr.trim();
let rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
let len = rawStr.length;
if (len % 2 !== 0) {
alert("存在非法字符!");
return "";
}
let curCharCode;
let resultStr = [];
for (let i = 0; i < len; i = i + 2) {
curCharCode = parseInt(rawStr.substr(i, 2), 16);
resultStr.push(String.fromCharCode(curCharCode));
}
return resultStr.join("");
}
/**
* hex转ArrayBuffer 蓝牙发送请求
*/
function hexToArrayBufferRequest(data) {
let buffer = new ArrayBuffer(data.length);
let dataViewLast = new DataView(buffer);
for (let i = 0; i < data.length; i++) {
dataViewLast.setUint8(i, data[i]);
}
return dataViewLast.buffer
}
/**
* 十进制转二进制
*/
function hex2binary(hex){
return (hex).toString(2)
}