I'm currently attempting to code a processor simulator in Java; including all of the different structures usually found in a CPU, including the ALU.
I'm having some difficulty working out how I would be able to represent 2's complement overflow in Java when dealing with subtraction. Addition is simple enough, if the result is above 255
then overflow has occurred, I have written code below to represent the process of addition:
public void addition()
{
byte a = aluA.getValue();
byte b = aluB.getValue();
if((a + b) > 255)
{
carryFlag = true;
}
byte r = (byte) (a + b);
aluR.setWrite();
aluR.loadValue(r);
System.out.println("[ALU] Addition operation completed successfully");
}
But I'm not sure how I should represent overflow when dealing with subtraction. As far as I know, subtraction overflow occurs in two situations:
- (+A) − (−B) = −C
- (−A) − (+B) = +C
But how do I represent this in Java, and does the way Java represents integers as 32-bit signed affect this?
The code I have below successfully subtracts the two bytes present in the ALU's registers, but I need a way of detecting when overflow has occurred.
public void subtraction()
{
byte a = aluA.getValue();
byte b = aluB.getValue();
if((a-b) == 0)
{
zeroFlag = true;
}
if((a-b) < 0)
{
negativeFlag = true;
}
byte r = (byte) (a - b);
aluR.setWrite();
aluR.loadValue(r);
System.out.println("[ALU] Subtraction operation completed successfully");
}