RoboGemp
RoboGemp

Reputation: 27

Need help getting the right result into 0500 address

Write an assembly language program that searches backwards through memory locations F454h - F503h for memory locations that contain the ASCII value for a lower case 'a' 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
dex

Loop:

lda 0F454h,x
cmp #'a'
bne NotA
inc 0500h

NotA:

dex
cpx #176d
bne Loop

brk

end

I'm not getting the correct result when I run this through the grader so any help is appreciated.

Upvotes: 0

Views: 64

Answers (1)

Guillermo Phillips
Guillermo Phillips

Reputation: 2216

There are two things to take into consideration.

  1. You want the starting address to be F503h and the ending address to be F454h.
  2. Ideally your loop exit condition should test either for the index being zero or negative (BNE or BPL). This is so that you can avoid using a compare (CPX).

If you test for negative, that basically means the top bit is set. The top bit gets set when the index (X) decrements from 00h to FFh.

Testing for negative would be preferable because the last value of the index (X) would be zero - which makes calculating the address to use (for LDA address,X) more obvious.

However, testing for negative means that the highest value X can be is 80h (128). This is because all values above 7Fh (127) have their top bit set. If you start at 80h then the first decrement (DEX) will take the index to 7Fh which is not negative, so the loop is good. If you start at say 81h, then the DEX will take the index to 80h, and this is negative (top bit set), so the loop exits immediately, which is bad.

So can we test for negative? In this case it's not possible. This is because the range of values for the index is F503h - F454h + 1= 176 (distinct addresses). And, this is above 128.

So we a forced to check for zero. That means the last value of the index (X) before we exit the loop will be 1.

In turn since we want to land on address F454h at the end of the loop, we must subtract 1 from this - since we are adding 1 from the index (X). So we need:

LDA F453h, X

What value of X do we start with? That is, how much do we need to add to F453h to get F503h? This is F503h - F453h = 176:

LDX #176d

Since X is not zero to start with, we need to set location 0500h to zero separately (or STZ 0500h on a 65C02):

LDA #0d
STA 0500h

The final algorithm becomes (I prefer capitals):

ORG 0200h
LDA #0d
STA 0500h
LDX #176d
Loop:
LDA F453h,X
CMP #'a'
BNE NotA
INC 0500h
NotA:
DEX
BNE Loop
BRK

Homework bonus: can you make the loop execute quicker?

Upvotes: 1

Related Questions