const BitArray = require('node-bitarray'); const range = require('range').range; export const Bit = { // returns a boolean array representing the bits of the input (MSB to LSB) parse(input: number, bitCount: number): boolean[] { const bits = []; let tmp = input; while (tmp > 0) { bits.push(tmp % 2); tmp = Math.floor(tmp / 2); } // prepend empty values to satisfy bitcount while (bitCount && bitCount > bits.length) { bits.push(0); } return bits.reverse(); } }; export function writeIntToBuffer(buffer: Buffer, value: number, writeLength: number, offset = 0): Buffer { const inputBits: number[] = BitArray.parse(value); const bufferBits = BitArray.fromBuffer(buffer).toArray(); if (inputBits.length > writeLength) { throw new Error(`Number must fit in provided space. Required space: ${inputBits.length}, available space: ${writeLength}`); } // pad inputbits with 0's to take up full writeLength range(writeLength - inputBits.length).map(() => inputBits.unshift(0)); // substitute appropriate part of config with input const newBufferBits = bufferBits .slice(0, offset) .concat(inputBits) .concat(bufferBits.slice(offset + writeLength)); return BitArray.factory(newBufferBits).toBuffer(); }