uniapp蓝牙传输中文乱码问题

问题描述:app接收到蓝牙传出过来的二进制数据,1.app进行arrbuff转成16进制字符串

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
    const hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function(bit) {
            return (00 + bit.toString(16)).slice(-2)
        }
    )
    return hexArr.join(‘‘)
}

2.将16进制的字符串转成10进制字符串这里需要特别注意(JS默认是Unicode编码的 也就是UTF-16)你看下你的设备传输过来的是什么编码

// 16进制转字符串
async function hexCharCodeToStr(hex) {
    var arr = hex.split(""),
        out = "",
        len = hex.length / 2;
    for (var i = 0; i < len; i++) {
        out += String.fromCharCode(parseInt(hex.substr(i * 2, 2), 16));
    }
    // 此时的out为UTF-8
    //蓝牙使用的是UTF-8编码
    // 解决乱码问题 (JS默认是Unicode编码的 也就是UTF-16)
    return await utf8to16(out)
}

3.解决中文乱码关键【这里以我自己举例,我对接的设备传输的编码是utf-8】我需要把UTF-8编码转成UTF-16下面提供两个方法

function utf8to16(str) {
    var out, i, len, c;
    var char2, char3;
    out = "";
    len = str.length;
    i = 0;
    while (i < len) {
        c = str.charCodeAt(i++);
        switch (c >> 4) {
            case 0:
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
                // 0xxxxxxx
                out += str.charAt(i - 1);
                break;
            case 12:
            case 13:
                // 110x xxxx 10xx xxxx
                char2 = str.charCodeAt(i++);
                out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
                break;
            case 14:
                // 1110 xxxx 10xx xxxx 10xx xxxx
                char2 = str.charCodeAt(i++);
                char3 = str.charCodeAt(i++);
                out += String.fromCharCode(((c & 0x0F) << 12) |
                    ((char2 & 0x3F) << 6) |
                    ((char3 & 0x3F) << 0));
                break;
        }
    }
    return out;
}

function utf16to8(str) {
    var out, i, len, c;
    out = "";
    len = str.length;
    for(i = 0; i < len; i++) {
    c = str.charCodeAt(i);
    if ((c >= 0x0001) && (c <= 0x007F)) {
    out += str.charAt(i);
    } else if (c > 0x07FF) {
    out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
    out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
    out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
    } else {
    out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
    out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
    }
    }
    return out;
}

 4,APP蓝牙发送数据给设备需要注意(因为js默认时utf-16的需要转成utf-8)在进行发送,否则设备端也解析不了

// 字符串转16进制(js字符串默认是Unicode编码utf16,需转成设备的utf8)解决中文问题
function strToHexCharCode(str) {
    //先把中文utf16转成utf8(解决中文问题)
    let utf8=utf16to8(str)
    
    if (utf8 === "")
        return "";
    var hexCharCode = [];
    // hexCharCode.push("0x");
    for (var i = 0; i < utf8.length; i++) {
        hexCharCode.push((utf8.charCodeAt(i)).toString(16));
    }
    return hexCharCode.join("");
}

 

uniapp蓝牙传输中文乱码问题

上一篇:ios 回退h5页面不刷新页面解决办法


下一篇:从 axios 源码中了解到的 Promise 链与请求的取消