简体   繁体   English

Javascript补码

[英]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.

相关问题 二进制补码相同的代码python / JavaScript不同的结果 - Twos complement same code python / JavaScript different results 二进制二进制补码解析为十进制? - Parsing of binary twos-complement number to decimal? Javascript 波浪号和二进制补码 - Javascript Tilde & Two's complement 这些JavaScript DNA补充算法是否等效且最优? - Are these javascript DNA complement algorithms equivalent & optimal? 如何构建Javascript体系结构以补充PHP MVC Web应用程序? - How to structure Javascript architecture to complement a PHP MVC web app? 如何将 BigInt 转换为 Javascript 中的二进制补码? - How to convert a BigInt, to two's complement binary in Javascript? 在没有 2 的补码的 Javascript 中对二进制字符串执行按位非运算 - Doing a bitwise NOT operation on a string in binary in Javascript without 2's complement 在JavaScript中打印8位字节的二进制补码二进制字符串 - Printing a two's complement binary string of an 8 bit byte in javascript 为什么Javascript将数字视为二进制补码 - Why does Javascript treat a number as a two's complement 我如何使用 32 位有符号整数的补码来表示 javascript 中的整数 - How do I use 32-bit signed integer's complement to represent an integer in javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM