"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getIntFromOP = exports.splitHexByNumber = exports.hex2IntArray = exports.hex2BigInt = exports.hex2Int = exports.asm2Int = exports.fromHex = exports.toHex = exports.hex2Bool = exports.bool2Hex = exports.int2Hex = exports.reverseHex = void 0;
function reverseHex(s) {
    s = s.length % 2 ? "0" + s : s;
    const array = [];
    for (let i = 0; i <= s.length - 2; i++) {
        if (i % 2 === 0)
            array.push(s.substring(i, i + 2));
    }
    return array.reverse().join("");
}
exports.reverseHex = reverseHex;
function int2Hex(num, byteSize, reverse = true) {
    let hex = num.toString(16);
    if (byteSize) {
        hex = ("0".repeat(byteSize * 4) + hex).slice(-byteSize * 2);
    }
    return reverse ? reverseHex(hex) : hex;
}
exports.int2Hex = int2Hex;
function bool2Hex(bool) {
    return bool ? "01" : "00";
}
exports.bool2Hex = bool2Hex;
function hex2Bool(hex) {
    return hex === "00" ? false : true;
}
exports.hex2Bool = hex2Bool;
function toHex(s) {
    return s
        .split("")
        .map(char => ("000" + char.charCodeAt(0).toString(16)).slice(-4))
        .join("");
}
exports.toHex = toHex;
function fromHex(s) {
    const chars = s.match(/.{1,4}/g) || [];
    return chars.map(char => String.fromCharCode(parseInt(char, 16))).join("");
}
exports.fromHex = fromHex;
/**
 * Converts an ASM number representation to a number
 * @param opcode OP_1 - OP_16 or hexadecimal number string
 * @returns parsed number
 */
function asm2Int(asm) {
    if (asm.startsWith("OP")) {
        const numString = asm.split("_")[1];
        return parseInt(numString);
    }
    else {
        return hex2Int(asm);
    }
}
exports.asm2Int = asm2Int;
function hex2Int(hex) {
    return parseInt("0x" + reverseHex(hex), 16);
}
exports.hex2Int = hex2Int;
function hex2BigInt(hex) {
    return BigInt("0x" + reverseHex(hex));
}
exports.hex2BigInt = hex2BigInt;
function hex2IntArray(hex, bytes = 1) {
    const byteChars = bytes * 2;
    return hex
        .split("")
        .reduce((shares, n, i) => (!(i % byteChars) ? shares.concat([hex.slice(i, i + byteChars)]) : shares), [])
        .map(x => parseInt(reverseHex(x), 16));
}
exports.hex2IntArray = hex2IntArray;
function splitHexByNumber(hex, length) {
    return hex.match(new RegExp(".{1," + length.toString() + "}", "g")) || []; // eslint-disable-line
}
exports.splitHexByNumber = splitHexByNumber;
function getIntFromOP(op) {
    return op.startsWith("OP") ? parseInt(op.slice(3)) : parseInt(op, 16);
}
exports.getIntFromOP = getIntFromOP;
//# sourceMappingURL=hex.js.map