Search code examples
assembly6502

Need help searching memory locations backwards (Assembly Language)


Problem: Write an assembly language program that uses a loop which searches backwards through memory locations E001h - E0FFh for locations that contain zeros and places the total into location 0500h. Have the program start at 0200h in memory. Assemble the program, load it into the emulator, run it, and verify that it works correctly.


    org 0200h

    ldx #0d
    stx 0500h
Loop:
    lda 0e001h,x

    cmp #0d
    bne NoZ

    inc 0500h

NoZ:
    dex

    bne Loop

    brk 

    end

I'm not too familiar with low level programming so I (believe) I managed to do this forward but I'm struggling on searching the memory locations backwards.


Solution

  • Your original code is not too bad, but has a bug. X wraps to FF so you check E100.

        org 0200h
        ldx #0d      ;I'm assuming this is 0 in an unusual decimal notation
        stx 0500h
    Loop:
        lda 0e001h,x ;x is 0,FF,FE...1. So E001,E100(bug),E0FF...E002
        cmp #0d
        bne NoZ
        inc 0500h
    NoZ:
        dex          ;x will wrap from 0 to FF
        bne Loop     ;x goes down to 1 (x=0 will break the loop)
        brk 
        end
    

    If this is homework, your instructor actually set you up for success. Loops in assembly are often more natural, smaller, and faster when counting in reverse.

        org 0200h
        ldx #0d
        stx 0500h    ;Initialize 0500 to 0
        dex          ;x starts at FF
    Loop:
        lda 0e000h,x ;Base address E000 and x is FF,FE...1. So E0FF,E0FE...E001
        cmp #0d
        bne NoZ
        inc 0500h
    NoZ:
        dex
        bne Loop     ;x goes down to 1 (x=0 will break the loop)
        brk 
        end
    

    The next optimization would be to use y for counting as per Eight-Bit Guru's answer.