uniapp藍牙傳輸中文亂碼問題
0 現狀
傳輸數字和字母的json字符串都可以解析,有個中文的硬件那邊就解析不了,替換一下發數據的處理函數即可
1 原先字符串轉化函數
const stringToBytes = (msg) => {const buffer = new ArrayBuffer(msg.length)const dataView = new DataView(buffer)for (var i = 0; i < msg.length; i++) {dataView.setUint8(i, msg.charAt(i).charCodeAt())}return buffer}
2 新的字符串替換函數
const stringToBytes = (msg) => {const bytes = [];for (let i = 0; i < msg.length; ++i) {const charCode = msg.charCodeAt(i);if (charCode < 0x80) {bytes.push(charCode);} else if (charCode < 0x800) {bytes.push(0xC0 | (charCode >> 6), 0x80 | (charCode & 0x3F));} else if (charCode < 0x10000) {bytes.push(0xE0 | (charCode >> 12),0x80 | ((charCode >> 6) & 0x3F),0x80 | (charCode & 0x3F));} else if (charCode < 0x200000) {bytes.push(0xF0 | (charCode >> 18),0x80 | ((charCode >> 12) & 0x3F),0x80 | ((charCode >> 6) & 0x3F),0x80 | (charCode & 0x3F));} else if (charCode < 0x4000000) {bytes.push(0xF8 | (charCode >> 24),0x80 | ((charCode >> 18) & 0x3F),0x80 | ((charCode >> 12) & 0x3F),0x80 | ((charCode >> 6) & 0x3F),0x80 | (charCode & 0x3F));} else {bytes.push(0xFC | (charCode >> 30),0x80 | ((charCode >> 24) & 0x3F),0x80 | ((charCode >> 18) & 0x3F),0x80 | ((charCode >> 12) & 0x3F),0x80 | ((charCode >> 6) & 0x3F),0x80 | (charCode & 0x3F));}}const buffer = new Uint8Array(bytes).buffer;return buffer;}
真的很神奇