编辑代码

// 实现一个二进制类:
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}`);
}

function logOperate(a, b, op) {
    var ba = new Binary(a),
        bb = new Binary(b),
        format = Binary.format,
        opList = {
           '&': (a, b) => a & b,
           '|': (a, b) => a | b,
           '^': (a, b) => a ^ b,
           '~': a => ~a,
           '<<': (a, b) => a << b,
           '>>': (a, b) => a >> b,
           '>>>': (a, b) => a >> b,
        },
        bop = new Binary(opList[op](a, b));

//  console.log(format(ba.getTrues(32)));
//  console.log(format(bb.getTrues(32)));
//  console.log(format(bop.getTrues(32)));

//  console.log(format(ba.getOnes(32)));
//  console.log(format(bb.getOnes(32)));
//  console.log(format(bop.getOnes(32)));
    console.group(`${a} ${op} ${b}:`);
    console.log(format(ba.getTwos(32)));
    console.log(format(bb.getTwos(32)));
    console.log(format(bop.getTwos(32))); 
    console.groupEnd(`${a} ${op} ${b}:`);   
}

logOperate(2, 3, '&');
logOperate(-2, -3, '&');
logOperate(2, 3, '|');
logOperate(-2, -3, '|');
logOperate(2, 0, '~');
logOperate(-2, -3, '^');
logOperate(2, 3, '<<');
logOperate(-2, 3, '<<');
logOperate(-5, 4, '>>');
logOperate(8, 3, '>>>');
logOperate(-8, 3, '>>>');