3 回答
TA贡献1851条经验 获得超5个赞
您需要将每个八位位组解析回数字,然后使用该值来获取字符,如下所示:
function bin2String(array) {
var result = "";
for (var i = 0; i < array.length; i++) {
result += String.fromCharCode(parseInt(array[i], 2));
}
return result;
}
bin2String(["01100110", "01101111", "01101111"]); // "foo"
// Using your string2Bin function to test:
bin2String(string2Bin("hello world")) === "hello world";
编辑:是的,您的当前时间string2Bin可以写得更短:
function string2Bin(str) {
var result = [];
for (var i = 0; i < str.length; i++) {
result.push(str.charCodeAt(i).toString(2));
}
return result;
}
但是通过查看您链接的文档,我认为该setBytesParameter方法期望blob数组包含十进制数字,而不是位字符串,因此您可以编写如下内容:
function string2Bin(str) {
var result = [];
for (var i = 0; i < str.length; i++) {
result.push(str.charCodeAt(i));
}
return result;
}
function bin2String(array) {
return String.fromCharCode.apply(String, array);
}
string2Bin('foo'); // [102, 111, 111]
bin2String(string2Bin('foo')) === 'foo'; // true
TA贡献1789条经验 获得超10个赞
只需apply将您的字节数组移至String.fromCharCode。例如
String.fromCharCode.apply(null, [102, 111, 111]) 等于'foo'。
警告:适用于小于65535的数组。MDN文档在此处。
TA贡献1909条经验 获得超7个赞
尝试使用新的文本编码API:
// create an array view of some valid bytes
let bytesView = new Uint8Array([104, 101, 108, 108, 111]);
console.log(bytesView);
// convert bytes to string
// encoding can be specfied, defaults to utf-8 which is ascii.
let str = new TextDecoder().decode(bytesView);
console.log(str);
// convert string to bytes
// encoding can be specfied, defaults to utf-8 which is ascii.
let bytes2 = new TextEncoder().encode(str);
// look, they're the same!
console.log(bytes2);
console.log(bytesView);
添加回答
举报