How do I store and retrieve a binary matrix in a JavaScript TypedArray?

Viewed 75

Suppose I have a binary matrix of size m by n. Each row is n bits long. I would like to store this matrix as space efficiently as possible while still being able to quickly retrieve individual rows. In particular I'd like to be able to do bitwise operations on the rows after retrieving them. To do this I'm using the JavaScript TypedArray.

My attempt at a solution is the following:

  1. Initialize the matrix to have a number of columns divisible by 8 (e.g by padding)
  2. Flatten the matrix row-wise (i.e put the rows side by side)
  3. Convert every 8 bits into an 8-bit integer, returning a flat array of 8-bit integers
  4. Initialize buffer and store the array of 8-bit integers as a u8int TypedArray

To retrieve a specific row i:

  1. Determine the number of 8-bit integers that constitute a single row (since I ensured the number of columns was divisible by 8, this should be a whole number). Call this rowLength.
  2. Find the offset indices for row i, where rowStartOffset = i*rowLength; rowEndOffset = (i+1)*rowLength-1 and slice the array
  3. Convert the integers in the array back into binary format
  4. Repeat 0-2 for more rows, then do bitwise operations on them

This works, but I wondered if there was a better way to do this. In particular is there a way to do bitwise operations without having to convert back into binary? (Currently I'm doing this by converting the integers into a binary string and then concatenating). Is there a method which does not use TypedArray?

0 Answers
Related