因为网上搜的很多教程都不靠,所以我自己写下这篇文章。
其实很简单:
/**
* objectToByte 对象格式转byte[]
* @param {Object} obj
*/
function objectToByte(obj) {
var bytes = new Array();
var len, c;
var arr = [];
for(let j in obj) {
arr.push(obj[j]);
console.log("obj[j]",obj[j]);
len = obj[j].length;
for (var i = 0; i < len; i++) {
c = obj[j].charCodeAt(i);
if (c >= 0x010000 && c <= 0x10FFFF) {
bytes.push(((c >> 18) & 0x07) | 0xF0);
bytes.push(((c >> 12) & 0x3F) | 0x80);
bytes.push(((c >> 6) & 0x3F) | 0x80);
bytes.push((c & 0x3F) | 0x80);
} else if (c >= 0x000800 && c <= 0x00FFFF) {
bytes.push(((c >> 12) & 0x0F) | 0xE0);
bytes.push(((c >> 6) & 0x3F) | 0x80);
bytes.push((c & 0x3F) | 0x80);
} else if (c >= 0x000080 && c <= 0x0007FF) {
bytes.push(((c >> 6) & 0x1F) | 0xC0);
bytes.push((c & 0x3F) | 0x80);
} else {
bytes.push(c & 0xFF);
}
}
}
console.log("arr",arr);
console.log("bytes",bytes);
return bytes;
}
拿去用吧