'Use a single character for use in a comparison statement - Assembly (Motorola 68k)
I have this C++ code I'm trying to replicate in Assembly (68K):
int main()
{
int i=0;
char *string = "This is a string"
while(string[i]!=' ')
{
/.../
i++;
}
return 0;
}
I'm stuck on the string[i]!=0
, indexing part of assembly. I need to CMP.B
with a letter string[i]
with some ' '
in memory. I tried CMP.B [STRING, D3],D5
with STRING
being the string stored as a variable, D3
being the current index as a number stored in a register and D5
being the empty space I'm comparing it with in a register,
Solution 1:[1]
CMP.B [STRING, D3],D5
This won't work: You need to use an address register and you cannot use a 32-bit offset when using a register.
Instead, load the address of STRING
into an address register - for example A4
:
LEA.L (STRING), A4
Then perform CMP.B (0,D3,A4),D5
EDIT
I don't know the assembler you are using. Using GNU assembler, the instruction CMP.B (0,D3,A4),D5
is writen as CMP.B (0,%D3,%A4),%D5
.
I just looked up the 68000 programmer's manual and it seems that the official syntax is: "CMP.B (0,A4,D3.L),D5
" (or "CMP.B (0,A4,D3.W),D5
" if only the low 16 Bits of D3
shall be used).
The instruction accesses the byte at the address A4+D3
, so if the register A4
contains the address of string[0]
(this means: A4
contains the value of the pointer string
!) and the register D3
contains the value i
, the instruction accesses the value string[i]
.
That value will be compared to the low 8 bits of D5
.
Solution 2:[2]
If string
is at a PC-relative address, you can write something like this:
cmp.b string(pc,d3.w),d5
But very often it is actually more efficient to load the address of the string into an address register and use post-increment addressing (it depends a bit on whether you finally need the address or the index of the first matching character.
moveq #' ',d5
lea string,a4 ; or string(pc)
loop:
cmp.b (a4)+,d5
bne.s loop
; now (a4,-1) has the address of the first space character
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | chtz |