UNPKG

@8kb/bit.io

Version:

`bit.io` is a js/ts library for reading individual bits from an `ArrayBuffer`.

31 lines (30 loc) 909 B
export const divide = (divident, divisor) => { const remainder = divident % divisor; return [ (divident - remainder) / divisor, remainder, ]; }; export const read_bit = (ab) => { const ua = new Uint8Array(ab); const bit_length = ab.byteLength * 8; return (index) => { if (index < 0 || index >= bit_length) return 'out of range'; if (!Number.isInteger(index)) return 'invalid index'; const [byte_index, bit_index] = divide(index, 8); const byte = ua[byte_index]; let result = byte << bit_index; result &= 255; return result >> 7; }; }; export const read_bits = (ab) => { const bit_length = ab.byteLength * 8; const read_bit_by_index = read_bit(ab); const result = []; for (let i = 0; i < bit_length; i++) result.push(read_bit_by_index(i)); return result; };