---
description: show 32-bit representation of signed integers.
---

# bitview()

[JS](../../../..) ⟩ [statement](../../../statement) ⟩ [expression](../../../statement/expr) ⟩ [operator](../..) ⟩ [arithmetic](..) ⟩ [bitwise]() ⟩ bitview

{% hint style="success" %}
show the <mark style="color:blue;">**32**</mark><mark style="color:red;">**-bit**</mark>**&#x20;**<mark style="color:yellow;">**representation**</mark> of an signed integer. :point\_right: [2s-complement](2s-complement "mention")

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

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

bitview(-1234).raw
// 11111111111111111111101100101110    // -1234 (= ~x + 1)
```
{% endhint %}

{% tabs %}
{% tab title="💾 程式" %}
* replit： [bitview()](https://replit.com/@pegasusroe/bitview#helpers/bitwise.js)

```javascript

// 📅 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 };

```
{% endtab %}

{% tab title="💈範例" %}
* replit： [bitview()](https://replit.com/@pegasusroe/bitview#index.js)

```javascript
const { bitview, bitIndices } = require('./helpers/bitwise.js');

// ⭐ test 32-bit signed integers
const M = 2 ** 32;           // 4294967296
const m = M/8;               //  536870912

// log
[
    bitview(M).indexed,   
    // ₁|⁹⁸⁷⁶⁵₄₃₂₁|⁹⁸⁷⁶⁵₄₃₂₁|⁹⁸⁷⁶⁵₄₃₂₁|
    // --------------------------------
    // 00000000000000000000000000000000    // M = 2^32
    
    bitview(m).indexed,    
    // ₁|⁹⁸⁷⁶⁵₄₃₂₁|⁹⁸⁷⁶⁵₄₃₂₁|⁹⁸⁷⁶⁵₄₃₂₁|
    // --------------------------------
    // 00100000000000000000000000000000    // m = M/8
    
    bitview(1234, {leadingZeros: false}).indexed,
    // |⁹⁸⁷⁶⁵₄₃₂₁|
    // -----------
    // 10011010010                         // 1234
    
    bitview(1234).indexed,
    bitview(~1234).raw,
    bitview(-1234).raw,
    // ₁|⁹⁸⁷⁶⁵₄₃₂₁|⁹⁸⁷⁶⁵₄₃₂₁|⁹⁸⁷⁶⁵₄₃₂₁|
    // --------------------------------
    // 00000000000000000000010011010010    //  1234
    // 11111111111111111111101100101101    // ~1234 (bits inverted)
    // 11111111111111111111101100101110    // -1234 (= ~x + 1)
    
    bitIndices({number: 1234}),
    // |⁹⁸⁷⁶⁵₄₃₂₁|
    // -----------
    bitview(1234, {leadingZeros: false}).raw,
    // 10011010010                         // 1234
    (1234).toString(2),                    // (same as above, but shorter)
    // 10011010010                         // 1234
    
    bitIndices(),                          // 32-bit bit indices
    // ₁|⁹⁸⁷⁶⁵₄₃₂₁|⁹⁸⁷⁶⁵₄₃₂₁|⁹⁸⁷⁶⁵₄₃₂₁|
    // --------------------------------
    
    bitview(-1).raw,
    // 11111111111111111111111111111111    // -1
    
    bitview(-2).equation,
    // (-2)₁₀ = (11111111111111111111111111111110)₂
    
    bitview(3, {leadingZeros: false}).equation,
    // (3)₁₀ = (11)₂

    '--------------------',

    // ❗ toString(2) doesn't show 2's complement for negative integers.
                                           // ┌─ ❗ minus sign (-) is kept.
    (-12).toString(2),                     // -1100    (what the ❗)
    (~~(-12)).toString(2),                 // -1100    (what the ❗)

    bitview(-1234).indexed,
    // ₁|⁹⁸⁷⁶⁵₄₃₂₁|⁹⁸⁷⁶⁵₄₃₂₁|⁹⁸⁷⁶⁵₄₃₂₁|
    // --------------------------------
    // 11111111111111111111101100101110    // -1234
    
    (-1234).toString(2),                   // -10011010010
    (-1234).toString(2).length,            // 12
    
].forEach(x => console.log(x));
```
{% endtab %}

{% tab title="🧨 雷區" %}
{% hint style="danger" %}
[num.toString(2)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString) <mark style="color:red;">**doesn't**</mark>**&#x20;**<mark style="color:yellow;">**show**</mark> <mark style="color:yellow;">**2**</mark><mark style="color:purple;">**'s complement**</mark> for <mark style="color:red;">**negative**</mark>**&#x20;**<mark style="color:yellow;">**integers**</mark>:exclamation:

```javascript
                              // ┌─ ❗ minus sign (-) is kept.
(-12).toString(2),            // -1100    (what the ❗)
(~~(-12)).toString(2),        // -1100    (what the ❗)
```
{% endhint %}
{% endtab %}

{% tab title="👥 相關" %}
* [not](not "mention") - inverts the bits.
* [double-tilde](not/double-tilde "mention") - nearest integer towards 0.
{% endtab %}

{% tab title="📗 參考" %}
* [ ] [javascript-the-definitive-guide](../../../../../master/ref/javascript-the-definitive-guide "mention") ⟩ 4.8.3 Bitwise Operators
* [ ] Cornell ⟩ [Two's Complement](https://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html)
* [ ] Wikipedia ⟩ [modulo operation](https://en.wikipedia.org/wiki/Modulo_operation), [modular arithmetic](https://en.wikipedia.org/wiki/Modular_arithmetic)
* [ ] Mastering JS ⟩ [How to Trim Leading Zeros from a String in JavaScript](https://masteringjs.io/tutorials/fundamentals/trim-leading-zeros)
{% endtab %}

{% tab title="📘 手冊" %}
* [Bitwise NOT (\~)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_NOT) - invert bits.
* [Number.prototype.toString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString) - specify the radix.
{% endtab %}

{% tab title="🗣 討論" %}
* [Remove/ truncate leading zeros by javascript/jquery](https://stackoverflow.com/questions/8276451/remove-truncate-leading-zeros-by-javascript-jquery)
{% endtab %}
{% endtabs %}
