[英]Javascript twos complement
The following python code seems to work very well to het the twos complement of a number: 以下python代码似乎可以很好地处理数字的二进制补码:
def twos_comp(self, val, bits):
if (val & (1 << (bits - 1))) != 0:
val -= 1 << bits
return val
It is used as num = self.twos_comp(int(binStr, 2), len(binStr))
where binStr is a string that contains an arbitrary length binary number. 它用作
num = self.twos_comp(int(binStr, 2), len(binStr))
,其中binStr是包含任意长度的二进制数的字符串。
I need to do the exact same thing in javascript (for node.js). 我需要在javascript中(对于node.js)做完全相同的事情。 I've been fighting it all day and am about to resign from the human race.
我整天都在为之奋斗,并准备从人类中辞职。 Clearly binary / bitwise math is not my strong suit.
显然,二进制/按位数学不是我的强项。
Could someone please assist so I can go on to more productive time wasting :-) 有人可以帮忙,我可以继续浪费更多时间:-)
function toTwosComplement(integer, numberBytes, dontCheckRange) {
// @integer - > the integer to convert
// @numberBytes -> the number of bytes representing the number (defaults to 1 if not specified)
var numberBits = (numberBytes || 1) * 8;
// make sure its in range given the number of bits
if (!dontCheckRange && (integer < (-(1 << (numberBits - 1))) || integer > ((1 << (numberBits - 1)) - 1)))
throw "Integer out of range given " + numberBytes + " byte(s) to represent.";
// if positive, return the positive value
if (integer >= 0)
return integer;
// if negative, convert to twos complement representation
return ~(((-integer) - 1) | ~((1 << numberBits) - 1));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.