Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert object to binary string

Here is how I compress binary string (char codes above 255) with pako:

var charData = xhr.responseText.split('').map(function(x){return x.charCodeAt(0);});
var binData = new Uint8Array(charData);
var data = pako.deflate(binData, {level:"9"});

Here is how I decompress data back:

var data2 = pako.inflate(xhr.responseText);

Now, how can I get original string in JavaScript from this object? I tried methods like this:

A.

pako.inflate(xhr.responseText, {to:"string"});

B.

String.fromCharCode.apply(null, data2);

C.

for (var i = 0, l = data2.length; i < l; i++)
{
result += String.fromCharCode(parseInt(array[i], 2));
}

All of these methods bring different data as JavaScript string than original. When I save decompressed pako.inflate(xhr.responseText) to a file (using functions with a.download) then dempressed file has exactly the same bytes as original file (so compression and decompression works correctly, without any byte modification).

like image 528
speedy Avatar asked Oct 31 '22 17:10

speedy


1 Answers

I am just trying to do the same and found a way to convert Object to binary string and vice versa. I just create a two function that converts JSON Object to Binary String and Binary String to JSON Object viz. covertObjectToBinary and convertBinaryToObject.

let obj = {a:1}
function covertObjectToBinary(obj) {
    let output = '',
        input = JSON.stringify(obj) // convert the json to string.
    // loop over the string and convert each charater to binary string.
    for (i = 0; i < input.length; i++) {
        output += input[i].charCodeAt(0).toString(2) + " ";
    }
    return output.trimEnd();
}

function convertBinaryToObject(str) {
    var newBin = str.split(" ");
    var binCode = [];
    for (i = 0; i < newBin.length; i++) {
        binCode.push(String.fromCharCode(parseInt(newBin[i], 2)));
    }
    let jsonString = binCode.join("");
    return JSON.parse(jsonString)
}
console.log('covertObjectToBinary =>', covertObjectToBinary(obj))
console.log('convertBinaryToObject =>', convertBinaryToObject(covertObjectToBinary(obj)))  
like image 141
Pulkit Aggarwal Avatar answered Nov 12 '22 14:11

Pulkit Aggarwal