use*_*579 69 javascript casting
如何将字节数组转换为字符串?
我发现这些功能正好相反:
function string2Bin(s) {
var b = new Array();
var last = s.length;
for (var i = 0; i < last; i++) {
var d = s.charCodeAt(i);
if (d < 128)
b[i] = dec2Bin(d);
else {
var c = s.charAt(i);
alert(c + ' is NOT an ASCII character');
b[i] = -1;
}
}
return b;
}
function dec2Bin(d) {
var b = '';
for (var i = 0; i < 8; i++) {
b = (d%2) + b;
d = Math.floor(d/2);
}
return b;
}
Run Code Online (Sandbox Code Playgroud)
但是如何让功能以其他方式运行?
谢谢.
邵
CMS*_*CMS 74
您需要将每个八位字节解析回数字,并使用该值来获取字符,如下所示:
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";
Run Code Online (Sandbox Code Playgroud)
编辑:是的,您的当前内容string2Bin
可以写得更快:
function string2Bin(str) {
var result = [];
for (var i = 0; i < str.length; i++) {
result.push(str.charCodeAt(i).toString(2));
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
但是通过查看你链接的文档,我认为该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
Run Code Online (Sandbox Code Playgroud)
Jam*_*mes 12
尝试使用新的文本编码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);
Run Code Online (Sandbox Code Playgroud)
Rou*_*man 12
这应该有效:
String.fromCharCode(...array);
Run Code Online (Sandbox Code Playgroud)
或者
String.fromCodePoint(...array)
Run Code Online (Sandbox Code Playgroud)
可以更简洁地编写string2Bin ,并且无需任何循环即可启动!
function string2Bin ( str ) {
return str.split("").map( function( val ) {
return val.charCodeAt( 0 );
} );
}
Run Code Online (Sandbox Code Playgroud)
字符串到字节数组: "FooBar".split('').map(c => c.charCodeAt(0));
字节数组转字符串: [102, 111, 111, 98, 97, 114].map(c => String.fromCharCode(c)).join('');
归档时间: |
|
查看次数: |
166661 次 |
最近记录: |