💾n.toHex()

to binary / octal / hex format.

JSvalueprimitivenumberfunctions ⟩ n.toHex()

convert to binary / octal / hex format (string).

// ⭐ getter/setter
Object.defineProperties(Number.prototype, {

    // n.binary
    binary: {
        get() { return this.toString(2) },
    },

    // n.octal
    octal: {
        get() { return this.toString(8) },
    },

    // n.hex
    hex: {
        get() { return this.toString(16).toUpperCase() },
    },

});

// ⭐ general function
function formatFunc(pre, base) {
    return function format({
        prefix = false,
        pad = { length: 0, char: '0' },
    } = {}) {
        // ⭐ `pad` might be overridden, better destructure again
        const { length = 0, char = '0' } = pad;
        return (prefix ? pre : '') + 
            this.toString(base).padStart(length, char).toUpperCase();
    }
}

// num.toBinary()
Number.prototype.toBinary = formatFunc('0b', 2);

// num.toOctal()
Number.prototype.toOctal = formatFunc('0o', 8);

// num.toHex()
Number.prototype.toHex = formatFunc('0x', 16);

// export nothing
module.exports = {};

💈範例:

(123).binary,    // '1111011'
(123).octal,     // '173'
(123).hex,       // '7B'

// binary
(12).toBinary(),                        // '1100'
(12).toBinary({ prefix: true }),        // '0b1100'
(12).toBinary({ pad: {length: 10} }),   // '0000001100'

(12).toBinary({                         // '0b0000001100'
    prefix: true,
    pad: { length: 10 },
}),

(12).toBinary({                         // '0b______1100'
    prefix: true,
    pad: { length: 10, char: '_' },
}),

// octal
(123).toOctal(),                        // 173
(123).toOctal({prefix: true}),          // 0o173
(123).toOctal({pad: {length: 10}}),     // 0000000173

(123).toOctal({                         // '0o0000000173'
    prefix: true,
    pad: { length: 10 },
}),

(123).toOctal({                         // '0o.......173'
    prefix: true,
    pad: { length: 10, char: '.' },
}),

// hex
(123).toHex(),                        // 7B
(123).toHex({prefix: true}),          // 0x7B
(123).toHex({pad: {length: 10}}),     // 000000007B

(123).toHex({                         // '0x000000007B'
    prefix: true,
    pad: { length: 10 },
}),

(123).toHex({                         // '0x________7B'
    prefix: true,
    pad: { length: 10, char: '_' },
}),

Last updated