0

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");
    }
Ahmad Al-Kurdi
  • 2,248
  • 3
  • 23
  • 39
  • 4
    Did you actually try any of this and step through the code in your IDE debugger? Do you realize in Java `byte` is _signed_ and its range is `[-128..+127]`, so the condition `(a + b) > 255` could never be true after sign-extending promotion to `int`? You can do what you want since at base level it's just bits in a register, but you cannot depend on `int` promotion and values to detect overflow. You have to do it with bit masks. – Jim Garrison Jan 22 '18 at 19:06
  • So I'm trying to create a processor simulator, would it be easier to do this with bitmasks or rewrite my register class so that each register is an array of 8 flipflop objects that simulate flipflop circuits and only hold a single bit? –  Jan 22 '18 at 21:01
  • Modeling individual flipflops is probably going a bit too far. To detect overflow in either direction consider masking all 8-bit values with `0x000000FF` _after_ promoting to int. Then you can detect overflow when the carry into the sign bit differs from the carry out of the sign bit. A full treatise on this is beyond the scope of SO – Jim Garrison Jan 22 '18 at 23:03

0 Answers0