编辑代码

// 实现一个二进制类:
function Binary(num, opt){
    this.num = num;
    this.opt = opt;
    this.binary_str = num.toString(2);
}

Binary.prototype.getTrues= function(bitwise) {
    var trues = '';
    if (this.num >= 0) {
        trues = (Array(bitwise).join("0") + this.binary_str).slice(-bitwise);
    }

    if(this.num < 0){
        trues = '1' + (Array(bitwise).join("0") + this.binary_str).slice(-(bitwise - 1)).replace('-',0);
    }
    return trues;
}

Binary.prototype.getOnes =function(bitwise) {
    var ones = '';
    if (this.num >= 0) {
        ones = (Array(bitwise).join("0") + this.binary_str).slice(-bitwise);
    }

    if(this.num <= 0){
        ones = '1' + (Array(bitwise).join("0") + this.binary_str).slice(-(bitwise - 1)).replace('-',0).split('').map(bit=>bit=='0'?'1':'0').join('');
    }
    return ones;
}

Binary.prototype.getTwos =function(bitwise) {
    var twos = '',
        parse_ones_add_1 = parseInt(this.getOnes(bitwise), 2) + 1;
    if (this.num >= 0) {
        twos = (Array(bitwise).join("0") + this.binary_str).slice(-bitwise);
    }

    if(this.num <= 0){
        twos = '1'+(Array(bitwise).join("0") + parse_ones_add_1.toString(2)).slice(-(bitwise - 1)).replace('-',0);
    }
    return twos;
}

Binary.prototype.toString = function(bitwise = 32) {
   var str = 
   `
   ======
    真值: ${this.binary_str};
    原码: ${this.getTrues(bitwise)};
    反码:${this.getOnes(bitwise)};
    补码:${this.getTwos(bitwise)};
   ======
   `;
   return str;
}

Binary.prototype.valueOf = function() {
   return parseInt(this.num, 10);
}

Binary.format = function(str = '', length = 4, replaceStr = ' ') {
    var reg = new RegExp(`(\\d)(?=(\\d{${length}})+(?!\\d))`, 'gi');
    return str.replace(reg, `$&${replaceStr}`);
}

var a = new Binary(+new Binary(-11123));
var format = Binary.format;
console.log(a.toString(32));
console.log(format(a.getTrues(32)));
console.log(format(a.getOnes(32)));
console.log(format(a.getTwos(32)));