
EXERCISES
1. Replace the following valid instruction with a single instruction that
has the same effect. Don’t consider the effect on flags.
push word L1
jmp L2
L1:
2. Replace the following invalid instructions with a single instruction
that has the same effect.
a. pop ip
b. mov ip, L5
c. sub sp, 2
mov [ss:sp], ax
d. mov ax, [ss:sp]
add sp, 2
e. add sp, 6
mov ip, [ss:sp-6]
3. Write a recursive function to calculate the Fibonacci of a number.
The number is passed as a parameter via the stack and the
calculated Fibonacci number is returned in the AX register. A local
variable should be used to store the return value from the first
recursive call. Fibonacci function is defined as follows:
Fibonacci(0) = 0
Fibonacci(1) = 1
Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2)
4. Write the above Fibonacci function iteratively.
HINT: Use two registers to hold the current and the previous
Fibonacci numbers in a loop.
5. Write a function switch_stack meant to change the current stack and
will be called as below. The function should destroy no registers.
push word [new_stack_segment]
push word [new_stack_offset]
call switch_stack
6. Write a function “addtoset” that takes offset of a function and
remembers this offset in an array that can hold a maximum of 8
offsets. It does nothing if there are already eight offsets in the set.
Write another function “callset” that makes a call to all functions in
the set one by one.
7. Do the above exercise such that “callset” does not use a CALL or a
JMP to invoke the functions.
HINT: Setup the stack appropriately such that the RET will execute
the first function, its RET execute the next and so on till the last RET
returns to the caller of “callset.”
8. Make an array of 0x80 bytes and treat it as one of 0x400 bits. Write
a function myalloc that takes one argument, the number of bits. It
finds that many consecutive zero bits in the array, makes them one,
and returns in AX the index of the first bit. Write another function
myfree that takes two arguments, index of a bit in the array, and the
number of bits. It makes that many consecutive bits zero, whatever
their previous values are, starting from the index in the first
argument.
9. [Circular Queue] Write functions to implement circular queues.
Declare 16x32 words of data for 16 queues numbered from 0 to 15.
Each queue has a front index, a rear index and 30 locations for data
totaling to 32 words. Declare another word variable whose 16 bits
correspond to the 16 queues and a 1 bit signals that the
corresponding queue is used and a 0 bit signals that it is free. Write
a function “qcreate” that returns a queue number after finding a free
queue or -1 if it failed. Write a function “qdestroy” that marks the
queue as free. Write two other functions “qadd” and “qremove” that