在JavaScript中减去有符号整数

时间:2012-02-26 20:23:05

标签: javascript bit-manipulation

我想在JavaScript中减去两个带符号的8位整数。由于JavaScript没有'signed'或'unsigned'整数的类型,我需要坚持'number'类型 - 并且不能像使用不同的语言那样做'cast-magic'。

我想模拟一种CPU寄存器,因此需要处理已签名的无符号值。另外,我需要计算Carry和Overflow标志的值。当无符号溢出(无符号值已经离开0到255的范围)时,进位标志置位,而溢出标志设置为有符号溢出(值为不在范围-128 - 127)。

这段代码看起来很有用,但是非常麻烦和丑陋。有没有“简单”的方法来进行这种计算?

提前致谢!

//Convert a signed 8bit number to a "real" number (254 => -2)
function toSigned(number)
{
    if (number & 0x80) //sign bit is set
        number = -(0x100 - number);
    return number
}
//Inverts the sign of a signed 8bit number
function invertSign(number)
{
    return 0x100 - number;
}
//subtracts source from target
function sub(target,source)
{
    //calculate carry
    var carry = (target - source < 0);
    console.log("Carry: %b", carry);

    //Calculate result & overflow
    var result = (target + invertSign(source)) & 0xFF;
    var overflow = !(result >= -128 && result <= 127);
    console.log("Overflow: %b", overflow);
    console.log("Result: %d - %d = %d",toSigned(target),toSigned(source),result);
}
//Examples
sub(8,254); //8 - (-2), no overflow, carry set
sub(8,2); //8 - 2, no overflow, no carry
sub(0x50,0xB0); //80 - (-80), overflow, carry

1 个答案:

答案 0 :(得分:1)

对您来说,最好的选择之一似乎是Typed Arrays(并非所有浏览器都完全支持,请参阅Can I Use: typedarrays

var signed8bitArray = new Int8Array(1);
var unsigned8bitArray = new Uint8Array(1);

unsigned8bitArray[0] = 254;
signed8bitArray[0] = unsigned8bitArray[0];
signed8bitArray[0] == -2 // This is true

您可能希望从MDN阅读Int8ArrayUint8Array和一般documentation on JavaScript typed arrays