how to convert ( to hack Assembler )

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

how to convert ( to hack Assembler )

ahmet
Hello Everyone.

I have these pseudo-codes for 4 problems, how can I implement them for the hack assembler ??

Thanks.

// Problem 1
// for loop

J=5
for(i=1; i<5; i++) {
                j--
}


// Problem 2
// if - then  - else

i=4
if (i < 5) then
                j = 3
else
                j = 2

 

// Problem 3
//while loop
i = 0
while(i==0) {
    j++
   if j = 5 then
                i = j
}


// Problem 4
// load and  traverse an array

A[0] =5
A[1]=4
A[2]=3
A[3]=2
A[4]=1
A[5]=0

for (i=0; i<=5; i++) {
                if A[i] == 0 then
                                A[i] = 5;
}
Reply | Threaded
Open this post in threaded view
|

Re: how to convert ( to hack Assembler )

cadet1620
Administrator
This post was updated on .
This looks like homework, so I won't be giving you solutions 8-).

First, read this Introduction to Hack Assembly Language.

It works best when writing asm to include your pseudocode in comments.  You first line,
j = 5
needs to set a memory variable 'j' to 5.  The Hack assembler assigns unique RAM addresses to symbols referenced in '@' commands that are not program labels, so this is simply
    // j = 5
    @5      // puts the constant 5 into A register
    D=A     // puts the constant 5 into D register
    @j      // puts RAM address of j in A register
    M=D     // writes D register to RAM[A]
    // for(i=1; i<5; i++) {
Once you get more comfortable with Hack asm, you won't want to put line-by-line detail comments in like the above sample, but they may be helpful at first.

For flow control code like for/if/while, rewrite you pseudocode using only if..goto since that's the only thing that the Hack CPU understands at the ASM level. For problem 1, that becomes something like
// Problem 1
    j = 5
    i = 1
CONTINUE:
    if i >= 5 goto BREAK
    j--
    i++
    goto CONTINUE
BREAK:

End your asm programs with an infinite loop so that the program does not run wild.
(HALT)
    @HALT
    0;JMP

--Mark
Reply | Threaded
Open this post in threaded view
|

Re: how to convert ( to hack Assembler )

ahmet
Hello cade

Yes, actually it is, But I thank you for the explanation.

I will work on this and do my best :)

Ahmet