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
To convert byte array to string in JavaScript, we can use the String. fromCharCode method. const s = String.
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".
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With