Hello everyone, I am new to this forum and a budding programmer. Currently, I am working on developing an app that can translate binary strings into English sentences. Here is the code snippet that I have been working on:
function binaryAgent(str) {
var binArr = str.split('');
var res = [];
var binary = [128, 64, 32, 16, 8 , 4, 2, 1];
var k = -1;
var matrix = [];
var noSpace = str.replace(/\s+/g, '');
for(var m=0; m<noSpace.length; m++){
if(m % 8 === 0){
k++;
matrix[k] = [];
}
matrix[k].push(noSpace[m]);
}
for(var i=0; i<matrix.length; i++){
for(var j=0; j<matrix[i].length; j++){
if(matrix[i][j] == 1){
res.push(binary[j]);
}
}
}
return res;
}
binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 001000
01100010 01101111 01101110 01100110 01101001 01110010 011001
01100011 01101111 01110011 00100000 01100110 01110101 011010
01101110 00100001 00111111");
In the second loop, I search through the 'matrix' array to identify values of 1. When found, I push the corresponding value from the 'binary' array. However, I have encountered a roadblock in one particular area.
The function returns an array 'res' containing all the values combined together:
[64, 1, 64, 32, 16, 2, 64, 32, 4, 1, 64, 32, 8, 4, 2, 32, 4, 2, 1, 64, 32, 16, 4, 32, 64, 32, 2, 64, 32, 8, 4, 2, 1, 64, 32, 8, 4, 2, 64, 32, 4, 2, 64, 32, 8, 1, 64, 32, 16, 2, 64, 32, 4, 1, 64, 32, 16, 2, 1, 32, 64, 32, 4, 2, 64, 32, 16, 4, 1, 64, 32, 8, 4, 2, 32, 1, 32, 16, 8, 4, 2, 1]
The problem lies in my inability to figure out how to sum the appropriate values within the 'res' array. My desired outcome would look something like this:
[[64, 1], [64, 32, 16, 2], [64, 32, 4, 1], [64, 32, 8, 4, 2] etc ..]
This would allow me to add up the values within each array and later utilize the fromCharCode() function to transform them into an English sentence.
Does anyone have a suggestion on how I can achieve an array structure like mentioned above? Or perhaps an alternate method to sum the relevant values?