2013-12-10 25 views
-1

这是我的功能。在这个函数中有两个参数值和多少位移位。javascript - 如何反转按位移?

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

现在我想使这个功能相反。在这个测试()函数,如果我把

test(105748,7); 

它返回13535744;

现在我需要做一个函数一样,如果我把

rev_test(13535744,7); 

返回105748;

任何帮助赞赏。

+2

你为什么把Python的标题? – Joe

回答

2

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

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 
+0

谢谢@Polywhirl – Shawon

+0

NP。 [查看此](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators)了解更多关于按位运算符的信息。 –

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