Thank you friends, now I understand. IM(very)HO the explanation in the book is very hard to understand, at a point that it seems wrong if one is not very knowledgeable with the topic.
BitWise wrote:
The CLC before the ADC is not needed as the carry must already be clear or the BCS would have been executed.
That's true! Thank you for pointing out!
John West wrote:
Your code is almost right. You have DVD and Q initialised correctly (although Q will become the remainder, not the quotient). But you're then subtracting the divisor from A, not Q. And you're incrementing Q, not DVD.
You could fix it by adding instructions to load A from Q and store it back:
Code:
Loop
ASL DVD
ROL Q
LDA Q
SEC
SBC DVS
BCS NxtPls
CLC
ADC DVS
JMP Skip
NxtPls
INC DVD
Skip
STA Q
Thak you very much for the explanation! I believe the code could be optimized by using:
Code:
...
ASL DVD
LDA Q
ROL
SEC
SBC DVS
...
rather than:
Code:
...
ASL DVD
ROL Q
LDA Q
SEC
SBC DVS
...
Right? I've implemented it and it seems to work well
- this is the code with more meaningful labels:
Code:
LDA #$00 ; will be my remainder
STA RMD
LDX #$08 ; how many loops
@Loop
ASL DVD/Q ; Shift Left DVD/Q (I named the Dividend "DVD/Q")
LDA RMD ;
ROL ; Rotate Left A (contains RMD)
SEC
SBC DVS ; MATH RMD = RMD - DVS
BCS @NxtPls ; MATH If C is still 1, no borrow occurred... move on to increase quotient ***
ADC DVS ; otherwise if C = 0, I've "used" it so I need to restore A
JMP @Skip
@NxtPls
INC DVD/Q ; ***
@Skip
STA RMD ; save RMD for next loop
DEX
BNE @Loop
Now I see the code from an "understanding it point of view" and I think that some optimization can be made:
Code:
LDA #$00 ; will be my remainder
; STA RMD ; don't need this right now
LDX #$08 ; how many loops
@Loop
ASL DVD/Q ; Shift Left DVD/Q (I named the Dividend "DVD/Q")
; LDA RMD ; RMD is already in A
ROL ; Rotate Left A (contains RMD)
SEC
SBC DVS ; MATH RMD = RMD - DVS
BCS @NxtPls ; MATH If C is still 1, no borrow occurred... move on to increase quotient ***
ADC DVS ; otherwise if C = 0, I've "used" it so I need to restore A
JMP @Skip
@NxtPls
INC DVD/Q ; ***
@Skip
; STA RMD ; no need to save RMD for next loop...
DEX
BNE @Loop
STA RMD ; at the end, I save A to RMD
Quote:
... so you don't have to shuffle it back and forth to memory all the time...
... and finally I came on my own to use A and save lot of cycles, just as per your suggestion.
Thank you both once again, now it's much clearer. I am very grateful to you. Time to move on to other exercises in Zaks' book!!!
Andrea