首页 > 解决方案 > 需要帮助向后搜索内存位置(汇编语言)

问题描述

问题:编写一个使用循环的汇编语言程序,该循环在内存位置 E001h - E0FFh 中向后搜索包含零的位置,并将总数放入位置 0500h。让程序从内存中的 0200h 开始。组装程序,将其加载到模拟器中,运行它,并验证它是否正常工作。


    org 0200h

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

    cmp #0d
    bne NoZ

    inc 0500h

NoZ:
    dex

    bne Loop

    brk 

    end

我对低级编程不太熟悉,所以我(相信)我设法做到了这一点,但我正在努力向后搜索内存位置。

标签: assembly6502

解决方案


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.


推荐阅读