hex转str
uniapp蓝牙项目,需要向蓝牙传递中文字符,并且接收蓝牙中文hex转成中文格式显示。
let readUTF = function(arr) {
if (typeof arr === 'string') {
return arr;
}
let UTF = '', _arr = arr;
for (let i = 0; i < _arr.length; i++) {
let one = _arr[i].toString(2), v = one.match(/^1+?(?=0)/);
if (v && one.length == 8) {
let bytesLength = v[0].length;
let store = _arr[i].toString(2).slice(7 - bytesLength);
for (let st = 1; st < bytesLength; st++) {
store += _arr[st + i].toString(2).slice(2)
}
UTF += String.fromCharCode(parseInt(store, 2));
i += bytesLength - 1
} else {
UTF += String.fromCharCode(_arr[i])
}
}
return UTF
}
// hexToString
let hexToString = function (str) {
if (str.length % 2 != 0) {
return console.log('必须为偶数');
}
let buf = [];
for (let i = 0; i < str.length; i += 2) {
buf.push(parseInt(str.substring(i, i + 2), 16));
}
return readUTF(buf);
}
调用方法:
hexToString('e4bda0e5a5bd')
// return 你好
str转hex
let bin2Hex = function (str) {
let re = /[\u4E00-\u9FA5]/
let ar = []
for (let i = 0; i < str.length; i++) {
let a = ''
if (re.test(str.charAt(i))) { // 中文
a = encodeURI(str.charAt(i)).replace(/%/g, '')
} else {
a = str.charCodeAt(i).toString(16)
}
ar.push(a)
}
str = ar.join('')
return str
}
调用方法:
bin2Hex ('你好')
// return E4BDA0E5A5BD