💾bitview()

show 32-bit representation of signed integers.

JSstatementexpressionoperatorarithmeticbitwise ⟩ bitview

show the 32-bit representation of an signed integer. 👉 2's complement

bitview(1234).indexed
// ₁|⁹⁸⁷⁶⁵₄₃₂₁|⁹⁸⁷⁶⁵₄₃₂₁|⁹⁸⁷⁶⁵₄₃₂₁|
// --------------------------------
// 00000000000000000000010011010010    //  1234

bitview(~1234).raw
// 11111111111111111111101100101101    // ~1234 (bits inverted)

bitview(-1234).raw
// 11111111111111111111101100101110    // -1234 (= ~x + 1)

// 📅 last updated: 2022.11.05

// bit view
function bitview(n, { 
    bits = 32,              // number of bits
    leadingZeros = true,    // keep leading zeros or not
} = {}) {

    const n0 = n;    // save original number
    let view = '';

    for (let i = 0; i < bits; i++) {
        let bit = n & 1;
        view = bit + view;
        n >>= 1;
    }

    const number = (!leadingZeros) ? n0 : undefined;

    // remove leading zeros if needed
    if (!leadingZeros) view = +view + '';
        
    // return object
    let result = {
        raw: `${view}`,
        // indexed: `${positions}\n${view}`,
        equation: `(${n0})₁₀ = (${view})₂`,
    };

    // result.indexed
    Object.defineProperty(result, 'indexed', {
        get() {
            const positions = bitIndices({number: number});
            return `${positions}\n${view}`;
        }
    })

    // return an object: {raw: , indexed: , equation: }
    return result;
}

// bit position
function bitIndices({
    bits = 32,    // number of bits
    number,       // let nunber decide # of bits
} = {}) {

    const digit = [
        '₀', '₁', '₂', '₃', '₄',
        '⁵', '⁶', '⁷', '⁸', '⁹',
    ];

    let result = '';
    let i = 0;            // position index
    
    // let `number` decide # of bits
    if (number !== undefined) 
        bits = bitview(number, {leadingZeros: false}).raw.length;
    
    let n = bits;
    while (n > 0) {
        result = (i === 0 ? '|' : digit[i]) + result;
        n -= 1;
        i += 1;
        if (i > 9) i = 0;
    }

    return result + `\n${'-'.repeat(bits)}`;
}

// export
module.exports = { bitview, bitIndices };

Last updated