Convert byte array to string in javascript

How to convert byte array to string?

I found these functions that do the opposite:

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 other functions to work?

Thank.

Shao

+57
javascript casting
Jul 07 2018-10-10T00:
source share
10 answers

You need to parse each octet back to the number and use this value to get the character, for example:

 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 briefly:

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

But, looking at the documentation-related one, I think the setBytesParameter method expects the blob array to contain decimal numbers, not a bit string, so you can 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 
+66
Jul 07 2018-10-07T00:
source share

Just apply your byte array to String.fromCharCode . for example

String.fromCharCode.apply(null, [102, 111, 111]) equals 'foo'.

Caution: works for arrays shorter than 65535. MDN docs here .

+28
May 31 '16 at 10:11
source share

This 2Bin line can be written even more succinctly and without any load cycles!

 function string2Bin ( str ) { return str.split("").map( function( val ) { return val.charCodeAt( 0 ); } ); } 
+7
Aug 10 2018-12-12T00:
source share

I think this would be more efficient:

 function toBinString (arr) { var uarr = new Uint8Array(arr.map(function(x){return parseInt(x,2)})); var strings = [], chunksize = 0xffff; // There is a maximum stack size. We cannot call String.fromCharCode with as many arguments as we want for (var i=0; i*chunksize < uarr.length; i++){ strings.push(String.fromCharCode.apply(null, uarr.subarray(i*chunksize, (i+1)*chunksize))); } return strings.join(''); } 
+3
Jun 13 '14 at 10:34
source share

Try the new text encoding 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); 
+3
Aug 09 '18 at 17:01
source share

Even if I was a little late, I thought that future users would be interested to share some of the single-line implementations that I used with ES6.

One thing that I consider important depending on your environment and / or what you will do with the data is storing the full byte value. For example, (5).toString(2) will give you 101 , but the full binary conversion is actually 00000101 , and so you might need to create an implementation of leftPad to fill the string byte with leading zeros. But you may not need this at all, as other answers have shown.

If you run the code snippet below, you will see that the first output is the conversion of the string abc to an array of bytes and immediately after that, the conversion of the specified array to the corresponding string again.

 // For each byte in our array, retrieve the char code value of the binary value const binArrayToString = array => array.map(byte => String.fromCharCode(parseInt(byte, 2))).join('') // Basic left pad implementation to ensure string is on 8 bits const leftPad = str => str.length < 8 ? (Array(8).join('0') + str).slice(-8) : str // For each char of the string, get the int code and convert it to binary. Ensure 8 bits. const stringToBinArray = str => str.split('').map(c => leftPad(c.charCodeAt().toString(2))) const array = stringToBinArray('abc') console.log(array) console.log(binArrayToString(array)) 
+1
Jul 08 '16 at 18:59
source share

String in byte array: "FooBar".split('').map(c => c.charCodeAt(0));

An array of bytes per line: [102, 111, 111, 98, 97, 114].map(c => String.fromCharCode(c)).join('');

+1
Oct 17 '18 at 15:11
source share

No solutions were found that would work with UTF-8 characters. String.fromCharCode is good until you come across a 2-byte character.

For example, Hรผser would look like [0x44,0x61,0x6e,0x69,0x65,0x6c,0x61,0x20,0x48,0xc3,0xbc,0x73,0x65,0x72]

But if you String.fromCharCode through String.fromCharCode you will be Hรƒยผser, since each byte will be converted to a character separately.

Decision

I am currently using the following solution:

 function pad(n) { return (n.length < 2 ? '0' + n : n); } function decodeUtf8(data) { return decodeURIComponent( data.map(byte => ('%' + pad(byte.toString(16)))).join('') ); } 
0
Oct 11 '18 at 14:01
source share

I had some decrypted byte arrays with padding characters and other things that I don't need, so I did this (probably not perfect, but this works for my limited use)

 var junk = String.fromCharCode.apply(null, res).split('').map(char => char.charCodeAt(0) <= 127 && char.charCodeAt(0) >= 32 ? char : '').join(''); 
0
Jan 15 '19 at 20:34
source share

Too late to answer, but if your input is in ASCII bytes, then you can try this solution:

 function convertArrToString(rArr){ //Step 1: Convert each element to character let tmpArr = new Array(); rArr.forEach(function(element,index){ tmpArr.push(String.fromCharCode(element)); }); //Step 2: Return the string by joining the elements return(tmpArr.join("")); } function convertArrToHexNumber(rArr){ return(parseInt(convertArrToString(rArr),16)); } 
0
Jan 22 '19 at 15:19
source share



All Articles