简体   繁体   中英

Emulating ADC instruction in Java

I'm attempting to create the MOS6502's ADC instruction in Java. More specifically the ADC decimal instruction, which uses BCD integer representation instead of 2's complement representation. This instruction is being modified to only be concerned with adding 8-bit numbers, not 16-bit like the normal instruction would.

I have the following code below that works successfully for adding 1+1 but outputs a 0 when attempting to add $49 (73) and 1 together, I'm not sure why this is happening.

In these tests, the carry bit is always set to 0.

private int adcDecimal(int a, int op)
    {
        System.out.println("[CPU] ADC-Decimal: " + a + " + " + op + " + " + getCarryBit());

        int tmp;
        int result;

        tmp = (a & 0x0f) + (op & 0x0f) + getCarryBit();
        if((tmp & 0xff) > 9) 
            tmp += 6;

        result = (tmp & 0x0f);
        result &= 0xff;

        setCarryFlag(tmp > 7);
        setZeroFlag(result == 0);
        setOverflowFlag(false);

        negativeFlag = (result & 0x80) != 0;

        System.out.println("[CPU] ADC-Decimal result: " + result);

        return result;
    }

Code:

public class MOS6502 {

    boolean negativeFlag;

    private int getCarryBit() { return 0; }
    private void setCarryFlag( boolean flag ) {}
    private void setZeroFlag( boolean flag ) {}
    private void setOverflowFlag( boolean flag ) {}

    private int adcDecimal( int a, int b ) {
        System.out.printf("[CPU] ADC-Decimal: %04X + %04X + %d",
            a, b, getCarryBit());
        int tmp =
            10*(( a & 0xf0 ) >> 4 ) +
                ( a & 0x0f ) +
            10*(( b & 0xf0 ) >> 4 ) +
                ( b & 0x0f ) +
            getCarryBit();
        setCarryFlag( tmp > 0x99 );
        int result = 0;
        int digit = 0;
        while( tmp > 0 ) {
            result |= (tmp % 10) << (4*digit++);
            tmp /= 10;
        }
        setZeroFlag( result == 0 );
        setOverflowFlag( false );
        negativeFlag = (result & 0x80) != 0;
        System.out.printf(", result: %04X\n", result);
        return result;
    }

    public static void main(String[] args) throws Exception {
        MOS6502 mos6502 = new MOS6502();
        mos6502.adcDecimal(    1,    1 );
        mos6502.adcDecimal(    1,    4 );
        mos6502.adcDecimal(    8,    5 );
        mos6502.adcDecimal( 0x48, 0x49 );
    }
}

Output:

$ javac MOS6502.java ; java MOS6502
[CPU] ADC-Decimal: 0001 + 0001 + 0, result: 0002
[CPU] ADC-Decimal: 0001 + 0004 + 0, result: 0005
[CPU] ADC-Decimal: 0008 + 0005 + 0, result: 0013
[CPU] ADC-Decimal: 0048 + 0049 + 0, result: 0097

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM