0

I have some understanding about bits and bytes, shifting concept and so - but no actual experience with it.

So:
I need to turn an array of true and false into a buffer, made of 1344 bits (which i send using UDP packets).

The other side will evaluate the buffer bit by bit..

Since i'm new to nodeJs, feel free to add tips or point me to new directions.

var arrBinary = new Array(1344);
for(i=0;i<1344;i++)arrBinary[i]=0;    
// some code here, which will turn some of the array's elements to 1

var arrForBuffer = new Array(168);
for(i=0;i<168;i++)arrForBuffer[i]=0;

var x = buffer.from(arr);

/****** the question ******/
// How to change and set arrForBuffer so it will represent the arrBinary Bits state?
yossi
  • 3,090
  • 7
  • 45
  • 65
  • 1
    Sounds like a dupe of https://stackoverflow.com/questions/17204912/javascript-need-functions-to-convert-a-string-containing-binary-to-hex-then-co – mplungjan Jul 31 '19 at 11:12

2 Answers2

2

You can use some bitshifting as you said:

// arrForBuffer must be initialized with 0s

for(let i = 0; i < 1344; i++) 
 arrForBuffer[ Math.floor(i / 8) ] += arrBinary[i] << (7 - (i % 8));

The first bit for example of arrBinary will be left shifted by 7 and added to the first byte, the second will be shifted left by 6, and so on. The 8th will be shifted left by 7 again, and will be added to the second byte.

It might be more readable (and possibly more performant), if it would be written as:

 for(let byte = 0; byte < 168; byte++) {
   arrForBuffer[byte] = 
     arrBinary[byte * 8 + 0] << 7 |
     arrBinary[byte * 8 + 1] << 6 |
     arrBinary[byte * 8 + 2] << 5 |
     arrBinary[byte * 8 + 3] << 4 |
     arrBinary[byte * 8 + 4] << 3 |
     arrBinary[byte * 8 + 5] << 2 |
     arrBinary[byte * 8 + 6] << 1 |
     arrBinary[byte * 8 + 7];
 } 
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • 1. thanks 2. i understand the concept, never used it and don't know the operators and how they work. can you please add some explanation to it? – yossi Jul 31 '19 at 11:19
1

Javascript supports bits operations like in every major language. You can use the | and << operators to achieve this transformation:

const size = 16;
const packsize = 8;

const arrBinary = new Array(size).fill(false);
arrBinary[2] = true;
arrBinary[6] = true;
arrBinary[8] = true;

let arrForBuffer = new Array(size / packsize);

let acc = 0;
let byteCounter = 0;

for (let i = 0; i < arrBinary.length; i++) {
  if (arrBinary[i]) {
    acc |= 1 << (i % packsize);
  }

  if (i % packsize == packsize - 1) {
    arrForBuffer[byteCounter] = acc;
    byteCounter++;
    acc = 0;
  }
}

for (let i = 0; i < arrForBuffer.length; i++) {
  console.log(`${i}: ${arrForBuffer[i]}`);
}
Jspdown
  • 424
  • 3
  • 11