内部表現

ビット演算の結果がよくわからなくて内部表現がどうなっているのかを文字列で返してくれる関数を書いたんだけど 32bit で表せる範囲に収まっているときにしか使えないし負数の場合の処理がアレなのであんまりうまくない…。ここらへんあんまりつっこまない方がいいのかなぁ。

Array.prototype.fill = function (v) {
    for(let i=-1,l=this.length-1 ; i<l ; this[++i]=v);
    return this;
};
String.prototype.x = function (num) {
    return Array(num).fill(this).join('');
};
String.prototype.zeroPadding = function (digit) {
    return '0'.x(digit - this.length) + this;
}
Number.prototype.zeroPadding = function (digit) {
    return this.toString().zeroPadding(digit);
};
Number.prototype.toInternalExp = function () {
    // init
    let n = this, s = false;
    if (n === 0) return '0';
    if (n < 0) n = -(n + 1), s = true;

    // to binary
    let t = [];
    while (n > 0) {
        t.push(n % 2);
        n = Math.floor(n / 2);
    }

    if (s) {
        // fill 0 in word length and flip bit
        for (let i=0, l=t.length ; i<l ; ++i) t[i] = ~(t[i]) & 0x01;
        t.push('1'.x(32 - t.length));
    }

    return t.reverse().join('');
};