javascript - 如何反转按位移位?

时间:2013-12-10 10:38:09

标签: javascript

这是我的功能。在此函数中,有两个参数值和多少位移位。

function test(Value, ShiftBits) {
 return (Value << ShiftBits) | (Value >>> (32 - ShiftBits));
};

现在我想反过来这个功能。在这个test()函数中,如果我把

test(105748,7);

它返回13535744;

现在我需要创建一个函数,如果我把

rev_test(13535744,7);

它返回105748;

任何帮助感谢。

2 个答案:

答案 0 :(得分:3)

为什么不扭转逻辑呢?我拼写出来如下:

Number.prototype.zeroFillBin = function() {
    var s = this.toString(2);
    while (s.length < 32) s = '0' + s;
    return s;
}

function test(val, bits) {
    return (val << bits) | (val >>> (32 - bits));
};

function rev_test(val, bits) {
    return (val >>> bits) | (val << (32 - bits));
};


x = 105748;
y = test(x, 7); // return 13535744
console.log(x + '   = ' + x.zeroFillBin())
console.log(y + ' = ' + y.zeroFillBin() + '\n');

x = 13535744;
y = rev_test(x, 7); // return 105748
console.log(x + ' = ' + x.zeroFillBin())
console.log(y + '   = ' + y.zeroFillBin() + '\n');

结果:

105748   = 00000000000000011001110100010100
13535744 = 00000000110011101000101000000000

13535744 = 00000000110011101000101000000000
105748   = 00000000000000011001110100010100

答案 1 :(得分:0)

105748 << 1 // 13535744
13535744 >> 1 // 105748