I am trying to convert this for loop in C++ to ASM:

for(x=y; (x>=y) && (array[x-z]>temp); x=x-z)
{
array[x] = array[x-z];
}

This is what I have so far:

mov   ax, y
mov   x, y

for_loop:
mov   ax, x
cmp   ax, z
jl        exit_for_loop
...........
.. Array access..
...........
mov   ax, x
mov   dx, z
sub     ax, dx
mov   x, ax
jmp   for_loop

I don't know how to incorporate "&&" with the code.
How and where in the code should I put it?
Thanks.

Edited 7 Years Ago by pokerstar: n/a

Something seems wrong with your C code.

x = y
while x >= y
x = x - z

If z < 0, one loop
if z > 0, many many loops

Despite your C code, Your assembly would be something similar to the following! If the entire C function was exposed in the post this code would most likely be much different! This is pretty much same functionality!

;for(x=y; (x>=y) && (array[x-z]>temp); x=x-z)
;   array[x] = array[x-z];

	mov	bx,x	; x
	mov	cx,z
	mov	dx,bx	; y
	neg	cx		; -z
	jmp	try

for_loop:
	mov		array[ bx ],ax		; ary[ x ]
	add		bx,cx				; x = x-z

try:
	cmp	bx,dx			; x<y ? Jump if true
	jb	done

	mov	ax,array[ bx+cx ]		; = ary[ x-z ]
	cmp	ax,temp
	ja	for_loop


done:

Edited 7 Years Ago by wildgoose: n/a

If this is C++ code/compiler then you should be able to instruct the compiler to stop before assembling, so the output should be in the form of a assembler code file..

For some reason my code still doesn't work.
Here's the C++ code I'm trying to convert, it's a version of shell sorting algorithm.

; while ( h>0 ) 
; {
;	for (i = h-1; i < length; i++) 
;	{
;		tmp = lst[i];
;		j = i;
;		
;		for ( j=i; (j>=h) && (lst[j-h]>tmp); j = j-h) 
;		{
;			lst[j] = lst[j-h];
;		}
;	
;		lst[j] = tmp;
;	}
;	
;	h = h / 3;
;
; }

Here's my effort so far:

while_lp2:
	mov	ax, h                           ;while(h>0)
	cmp	ax, wzero
	jle	exit_while2
	
	sub	ax, 1                           ;for(i=h-1)
	mov	i, ax
for_lp1:
	cmp	ax, len                        ;i < length
	jge	exit_for1
	mov	si,i
	mov	ax, word ptr[bx][si]    
	mov	tmp, ax                       ;tmp = lst[i]
	mov	j, si                             ;j=i

	mov	ax, i                            ;for(j=i)
	mov	j, ax
	mov	dx, h
	sub	ax, dx
	mov	di, ax
for_lp2:
	mov	ax, j                            ;j>=h
	cmp	ax, h
	jl	exit_for2
	mov	ax, word ptr[bx][di]
	cmp	ax, tmp                       ;lst[j-h] > tmp
	jle	exit_for2
	mov	si, j
	mov	word ptr[bx][si], ax     ;lst[j] = lst[j-h]
	mov	j, di                              ;j = j-h
	jmp	for_lp2
exit_for2:

	mov	si, j                               ;lst[j] = tmp;
	mov	ax, tmp
	mov	word ptr[bx][si], ax

	inc	i                                     ;i++
	jmp	for_lp1
exit_for1:

	mov	ax, h
	cwd
	idiv	wthree
	mov	h, ax                               ;h = h / 3;
	jmp	while_lp2
exit_while2:

It still won't sort the right way.
I'm really getting frustrated now. Sorry.
What is it that I'm doing wrong?

This article has been dead for over six months. Start a new discussion instead.