UNPKG

@signumjs/util

Version:

Useful utilities and tools for building Signum Network applications

45 lines 1.85 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.convertDecStringToHexString = void 0; /** Original work Copyright (c) 2020 Burst Apps Team */ require("./internal/padStartPolyfill"); const bignumber_js_1 = __importDefault(require("bignumber.js")); const twosComplementBinary_1 = require("./internal/twosComplementBinary"); /** * Arbitrary length decimal to hexadecimal conversion * * > Negative numbers are expressed as Two's Complement (https://en.wikipedia.org/wiki/Two%27s_complement) * * Credits to AJ ONeal for the two's complements stuff * https://coolaj86.com/articles/convert-decimal-to-hex-with-js-bigints/ * * @param decimal A decimal string or BigNumber representation * @param padding If set the hex string will be padded to given number, 8 or 16 or more * @return A hexadecimal string * * @category conversion */ const convertDecStringToHexString = (decimal, padding = 2) => { let bn = typeof decimal === 'string' ? new bignumber_js_1.default(decimal) : decimal; if (bn.isNaN()) { throw new Error(`Invalid decimal argument: [${decimal}] - Expected a valid decimal value`); } if (padding < 0) { throw new Error(`Invalid padding argument: [${padding}] - Expected a positive value`); } const isNegative = bn.lt(0); if (isNegative) { bn = (0, twosComplementBinary_1.twosComplementBinary)(bn); } const hex = bn.toString(16); const padSize = Math.ceil(hex.length / padding); // @ts-ignore return hex.padStart(padSize * padding, isNegative ? 'f' : '0'); }; exports.convertDecStringToHexString = convertDecStringToHexString; //# sourceMappingURL=convertDecStringToHexString.js.map