uniapp蓝牙传输中文乱码问题
0 现状
传输数字和字母的json字符串都可以解析,有个中文的硬件那边就解析不了,替换一下发数据的处理函数即可
1 原先字符串转化函数
js
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 新的字符串替换函数
js
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;
}
真的很神奇