views:

216

answers:

4

I have just started a part time course and I have limited class time. I am really stuck on this question, any help solving it is greatly appreciated!

here's the question....

(a) write a subprogram which will take one argument, x, and return x*3 + 1. I.e. a Java method would be

int fun(int x){
return x*3 + 1;
}

(b) Write a fragment of code which will set variable a0 to 5 and then call fun on a0 and put the result in a1.

a1 = fun(a0);
+5  A: 

For the first question, first multiply the register holding the value by 2 using shifting (or adding the register to itself), then add the original value. After this, increase the register by one. I don't know which processor you are targeting but in Z80 it would be something like this (assuming data in A register):

ld b,a
sla a   ;or: add a,a
add a,b
inc a
Konamiman
+1 for providing a solution in Z80 assembler.
Joachim Sauer
It's the only assembler I know anyway... :)
Konamiman
A: 

you could just decompile and look at the assembler. google java decompiler

Esben Skov Pedersen
A: 

The first two things you should investigate are:

  1. Which processor are you writing code for (which gives you the instruction set). Then check out interesting instructions there, like add, multiply, etc. Depending on the processor, you will probably also need a few less obvious one, like return, set up stack frame, etc.
  2. Which calling convention do you have to adhere to?
erikkallen
+1  A: 

And for Intel x86 and later CPUs is...

  lea   eax, eax * 2 + eax + 1

GJ

GJ