"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setToBitFlags = exports.getNumBitsOfN = exports.getKBitOfN = exports.countSetBits = exports.convertDecimalToBinary = exports.convertBinaryToDecimal = exports.arrayToBitFlags = void 0;
const flag_1 = require("./flag");
const utils_1 = require("./utils");
/** Helper function to convert a set of flags to a single `BitFlags` object. */
function arrayToBitFlags(array) {
    let flags = 0;
    for (const flag of array) {
        flags = (0, flag_1.addFlag)(flags, flag);
    }
    return flags;
}
exports.arrayToBitFlags = arrayToBitFlags;
/** Helper function to convert an array of bits to the resulting decimal number. */
function convertBinaryToDecimal(bits) {
    const bitsString = bits.join("");
    return Number.parseInt(bitsString, 2);
}
exports.convertBinaryToDecimal = convertBinaryToDecimal;
/**
 * Helper function to convert a number to an array of bits.
 *
 * @param num The number to convert.
 * @param minLength Optional. Equal to the minimum amount of bits that should be returned. If the
 *                  converted number of bits is below this number, 0's will be padded to the left
 *                  side until the minimum length is met. Default is undefined (which will not cause
 *                  any padding).
 */
function convertDecimalToBinary(num, minLength) {
    const bits = [];
    const bitsString = num.toString(2);
    for (const bitString of bitsString) {
        const bit = tonumber(bitString);
        (0, utils_1.assertDefined)(bit, `Failed to convert the following number to binary: ${num}`);
        bits.push(bit);
    }
    if (minLength !== undefined) {
        while (bits.length < minLength) {
            bits.unshift(0);
        }
    }
    return bits;
}
exports.convertDecimalToBinary = convertDecimalToBinary;
/**
 * Helper function to count the number of bits that are set to 1 in a binary representation of a
 * number.
 */
function countSetBits(num) {
    let count = 0;
    while (num > 0) {
        num &= num - 1;
        count++;
    }
    return count;
}
exports.countSetBits = countSetBits;
/** Helper function to get the value of a specific but in a binary representation of a number. */
function getKBitOfN(k, n) {
    return (n >>> k) & 1;
}
exports.getKBitOfN = getKBitOfN;
/** Helper function to get the number of bits in a binary representation of a number. */
function getNumBitsOfN(n) {
    let numBits = 0;
    while (n > 0) {
        numBits++;
        n >>>= 1;
    }
    return numBits;
}
exports.getNumBitsOfN = getNumBitsOfN;
/** Helper function to convert a set of flags to a single `BitFlags` object. */
function setToBitFlags(set) {
    let flags = 0;
    for (const flag of set) {
        flags = (0, flag_1.addFlag)(flags, flag);
    }
    return flags;
}
exports.setToBitFlags = setToBitFlags;
