js将字符串数字数组转换成uint8Array数组,用于mcu通讯指令。
将字符串数字数组转换成uint8Array
function toUint8Array(data) {
let buffer;
if (typeof data === 'string') {
const textEncoder = new TextEncoder();
buffer = textEncoder.encode(data).buffer;
} else if (typeof data === 'number') {
let byteLength;
if (data >= 0 && data <= 255) { // 8位数字
byteLength = 1;
} else if (data >= 0 && data <= 65535) { // 16位数字
byteLength = 2;
} else if (data >= 0 && data <= 4294967295) { // 32位数字
byteLength = 4;
} else { // 64位数字
byteLength = 8;
}
buffer = new ArrayBuffer(byteLength);
const dataView = new DataView(buffer);
if (byteLength === 1) {
dataView.setUint8(0, data);
} else if (byteLength === 2) {
dataView.setUint16(0, data, false);
} else if (byteLength === 4) {
dataView.setUint32(0, data, false);
} else {
dataView.setBigUint64(0, BigInt(data), false);
}
} else if (Array.isArray(data)) {
buffer = new ArrayBuffer(data.length);
const uint8Array = new Uint8Array(buffer);
for (let i = 0; i < data.length; i++) {
uint8Array[i] = data[i];
}
} else {
throw new Error('Unsupported data type');
}
return new Uint8Array(buffer);
}
使用:
toUint8Array('vsay');
//输出 [118, 115, 97, 121]
toUint8Array(257);
//输出 [1, 1] 二进制 00000001 00000001
将uint8Array转换成字符串
function Uint8ArrayToString(data) {
// Uint8Array,存储了 UTF-8 编码的汉字数据
const dataArray = new Uint8Array(data);
// 找到第一个为 0 的字节的索引
const zeroIndex = dataArray.findIndex(byte => byte === 0);
// 截断数组到第一个 0 的位置
const trimmedArray = dataArray.slice(0, zeroIndex !== -1 ? zeroIndex : dataArray.length);
// 创建一个 TextDecoder 对象,指定 UTF-8 编码
const decoder = new TextDecoder('utf-8');
// 解码截断后的 remark 数据
return decoder.decode(trimmedArray);
}
使用:
Uint8ArrayToString([65,66,67,68,69,70]);
//输出 'ABCDEF'