在javascript中将字节数组转换为字符串

如何将字节数组转换为字符串?


我发现这些功能相反:


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;

}

但是,如何使功能以其他方式起作用?


谢谢。


o


千万里不及你
浏览 6253回答 3
3回答

江户川乱折腾

您需要将每个八位位组解析回数字,然后使用该值来获取字符,如下所示:function bin2String(array) {&nbsp; var result = "";&nbsp; for (var i = 0; i < array.length; i++) {&nbsp; &nbsp; result += String.fromCharCode(parseInt(array[i], 2));&nbsp; }&nbsp; return result;}bin2String(["01100110", "01101111", "01101111"]); // "foo"// Using your string2Bin function to test:bin2String(string2Bin("hello world")) === "hello world";编辑:是的,您的当前时间string2Bin可以写得更短:function string2Bin(str) {&nbsp; var result = [];&nbsp; for (var i = 0; i < str.length; i++) {&nbsp; &nbsp; result.push(str.charCodeAt(i).toString(2));&nbsp; }&nbsp; return result;}但是通过查看您链接的文档,我认为该setBytesParameter方法期望blob数组包含十进制数字,而不是位字符串,因此您可以编写如下内容:function string2Bin(str) {&nbsp; var result = [];&nbsp; for (var i = 0; i < str.length; i++) {&nbsp; &nbsp; result.push(str.charCodeAt(i));&nbsp; }&nbsp; return result;}function bin2String(array) {&nbsp; return String.fromCharCode.apply(String, array);}string2Bin('foo'); // [102, 111, 111]bin2String(string2Bin('foo')) === 'foo'; // true

至尊宝的传说

只需apply将您的字节数组移至String.fromCharCode。例如String.fromCharCode.apply(null, [102, 111, 111]) 等于'foo'。警告:适用于小于65535的数组。MDN文档在此处。

jeck猫

尝试使用新的文本编码API:// create an array view of some valid byteslet 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);&nbsp;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);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript