UNPKG

lotus-sdk

Version:

Central repository for several classes of tools for integrating with, and building for, the Lotusia ecosystem

27 lines (26 loc) 892 B
import { Preconditions } from './preconditions.js'; export function convertBits(data, from, to, strict = false) { let accumulator = 0; let bits = 0; const result = []; const mask = (1 << to) - 1; for (let i = 0; i < data.length; i++) { const value = data[i]; Preconditions.checkArgument(!(value < 0 || value >> from !== 0), 'value', `value ${value}`); accumulator = (accumulator << from) | value; bits += from; while (bits >= to) { bits -= to; result.push((accumulator >> bits) & mask); } } if (!strict) { if (bits > 0) { result.push((accumulator << (to - bits)) & mask); } } else { Preconditions.checkState(!(bits >= from || (accumulator << (to - bits)) & mask), 'Conversion requires padding but strict mode was used'); } return result; }