Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting byte array to string in javascript

How do I convert a byte array into a string?

I have found these functions that do the reverse:

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; } 

But how do I get the functions working the other way?

Thanks.

Shao

like image 467
user385579 Avatar asked Jul 07 '10 14:07

user385579


People also ask

How to convert byte array into string in JavaScript?

To convert byte array to string in JavaScript, we can use the String. fromCharCode method. const s = String.

What is byte array in JavaScript?

The ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. It is an array of bytes, often referred to in other languages as a "byte array".


1 Answers

You need to parse each octet back to number, and use that value to get a character, something like this:

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"; 

Edit: Yes, your current string2Bin can be written more shortly:

function string2Bin(str) {   var result = [];   for (var i = 0; i < str.length; i++) {     result.push(str.charCodeAt(i).toString(2));   }   return result; } 

But by looking at the documentation you linked, I think that the setBytesParameter method expects that the blob array contains the decimal numbers, not a bit string, so you could write something like this:

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 
like image 138
Christian C. Salvadó Avatar answered Sep 28 '22 01:09

Christian C. Salvadó