CS 301 - Homework 3 Solutions

# CS 301 Homework 3 Solution -- problem 1
#  Orion Sky Lawlor, olawlor@acm.org, 2005/10/05 (Public Domain)
.section ".text"
.globl foo
.type foo,@function

foo:


mov $0x0001,%eax

ret
# CS 301 Homework 3 Solution -- problem 2
#  Orion Sky Lawlor, olawlor@acm.org, 2005/10/05 (Public Domain)
.section ".text"
.globl foo
.type foo,@function

foo:


mov $0x15,%eax   # Note: hex constants need "0x" just like in C/C++!
mov $0x23,%ebx
add %ebx,%eax

ret

# CS 301 Homework 3 Solution -- problem 3
#  Orion Sky Lawlor, olawlor@acm.org, 2005/10/05 (Public Domain)
.section ".text"
.globl foo
.type foo,@function

foo:


call read_input  # Returns input value in %eax
add %eax,%eax    # x<<1 == x*2 == x+x

ret

# CS 301 Homework 3 Solution -- Problem 4
#  Orion Sky Lawlor, olawlor@acm.org, 2005/10/05 (Public Domain)
.section ".text"
.globl foo
.type foo,@function

foo:


call read_input   # Returns integer in eax
cmp $2,%eax    
jge bigenough     # Skip next line if eax>=2
mov $2,%eax       # Set eax to 2 if it's too small
bigenough:


ret

# CS 301 Homework 3 Solution -- Problem 5
#  Orion Sky Lawlor, olawlor@acm.org, 2005/10/05 (Public Domain)
.section ".text"
.globl foo
.type foo,@function

foo:


call read_input
# ecx is counter (counts down)
# eax is sum
mov %eax,%ecx 
mov $0,%eax   # WARNING: registers start with random values on x86, not 0 like UEMU!

jmp Lmid  # %ecx == n, but we want to start with n-1, so decrement first

Lstart:    # Start of loop
  add %ecx,%eax  
Lmid:
  dec %ecx   # SUBTLE: sets flags like "cmp $0,%eax"
  jg Lstart  # Go back to start until ecx<=0

ret

O. Lawlor, ffosl@uaf.edu
Up to: Class Site, CS, UAF