I want to subtract two signed 8bit integers in JavaScript. As JavaScript doesn’t have a type for ‘signed’ or ‘unsigned’ integers I need to stick to the ‘number’ type – and cannot do some ‘cast-magic’ just like it would be possible using different languages.
I want to simulate a kind of CPU register and therefore need to work on as well the signed as the unsigned values. Additionally I need to calculate the values of the Carry and the Overflow flag. The Carry Flag is set when an unsigned overflow happens (the unsigned value has left the range from 0 to 255) while the Overflow Flag is set on a signed overflow (value is not is not in range -128 – 127).
This code seems to work but is quite cumbersome and ugly. Is there any “easy” way of doing this calculation?
Thanks in advance!
//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
It seems that one of best options for you is
Typed Arrays(it’s not completely supported by all browsers, see Can I Use:typedarrays)You may want to read
Int8Array,Uint8Arrayand general documentation on JavaScript typed arrays from MDN.