Converting Byte Array to String in JavaScript

Converting byte array to string in javascript

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

how to turn an array of bytes into a string in javascript

Each "byte" in your array is actually the ASCII code for a character. String.fromCharCode will convert each code into a character.

It actually supports an infinite number of parameters, so you can just do:

String.fromCharCode.apply(String, arr);

When ran on your array you get: "Invalid password".

As @Ted Hopp points out, the 0 at the end is going to add a null character to the string. To remove it, just do: .replace(/\0/g,'').

String.fromCharCode.apply(String, arr).replace(/\0/g,'');

Byte array to Hex string conversion in javascript

You are missing the padding in the hex conversion. You'll want to use

function toHexString(byteArray) {
return Array.from(byteArray, function(byte) {
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join('')
}

so that each byte transforms to exactly two hex digits. Your expected output would be 04812d7e3a9829e5d51bdd64ceb35df060699bc1309731bd6e6f1a5443a7f9ce0af4382fcfd6f5f8a08bb2619709c2d49fb771601770f2c267985af2754e1f8cf9

Converting a larger byte array to a string

The problem is caused because implementations have limits to the number of parameters accepted. This results in an exception being raised when too many parameters (over ~128k in this case) are supplied to the String.fromCodePoint functions via the spread operator.

One way to solve this problem relatively efficiently, albeit with slightly more code, is to batch the operation across multiple calls. Here is my proposed implementation, which fixes what I perceive as issues relating to scaling performance and the handling of surrogate pairs (that's incorrect: fromCodePoint doesn't care about surrogates, making it preferable to fromCharCode in such cases).

let N = 500 * 1000;
let A = [...Array(N)].map((x,i) => i); // start with "an array".

function codePointsToString(cps) {
let rs = [];
let batch = 32767; // Supported 'all' browsers
for (let i = 0; i < cps.length; ){
let e = i + batch;
// Build batch section, defer to Array.join.
rs.push(String.fromCodePoint.apply(null, cps.slice(i, e)));
i = e;
}
return rs.join('');
}

var result = codePointsToString(A);
console.log(result.length);

Also, I wanted a trophy. The code above should run in O(n) time and minimize the amount of objects allocated. No guarantees on this being the 'best' approach. A benefit of the batching approach, and why the cost of apply (or spread invocation) is subsumed, is that there are significantly less calls to String.fromCodePoint and intermediate strings. YMMV - especially across environments.

Here is an online benchmark. All tests have access to, and use, the same generated "A" array of 500k elements.

Sample Image

convert a byte array to string

You could convert the byte array to a char array, and then construct a string from that

scala> val bytes = Array[Byte]('a','b','c','d')
bytes: Array[Byte] = Array(97, 98, 99, 100)

scala> (bytes.map(_.toChar)).mkString
res10: String = abcd

scala>

How to convert an array of bytes into string with Node.js?

randbytes works asynchronously. If you want to combine it with promises, you need to use a Promises-lib as well. I'm using when as an example:

var when          = require('when');
var RandBytes = require('randbytes');
var randomSource = RandBytes.urandom.getInstance();

function get_rand() {
var dfd = when.defer();
randomSource.getRandomBytes(20, function(bytes) {
dfd.resolve( bytes.toString('hex') ); // convert to hex string
});
return dfd.promise;
}

// example call:
get_rand().then(function(bytes) {
console.log('random byte string:', bytes);
});


Related Topics



Leave a reply



Submit