Programming
Math pow in Assembly
I was programming some assembly the other day, and I noticed this specific example cannot be found anywhere! So I thought I’d post it
To run… save the file as power.s, then run
gcc -o power.o power.s -m32
(-m32 only if your on a 64bit system)
chmod +x power.o ./power.o
power.s
# ************************************************************************
# * Program name : pow *
# * Description : Assembly Power function *
# * Author : nicktc@gmail.com *
# * Date : 2011-05-26 *
# * License : CC BY-NC-SA http://www.creativecommons.org *
# ************************************************************************
.text
asknrstr: .asciz "Please enter a natural number:"
asknrstr2: .asciz "To the power of:"
printnrstr: .asciz "%d^%d="
formatstr: .asciz "%d" # Used in inout subroutine
.global main
# ************************************************************************
# * Subroutine : main *
# * Description : application entry point *
# ************************************************************************
main: movl %esp, %ebp # initialize the base pointer
ask:
# Get number
pushl $asknrstr # Push ask string
call printf # Pop and print ask string
subl $4,%esp # Reserve stack space for int
leal -4(%ebp), %eax # Load address of stack space into %eax
pushl %eax # Push argument of scanf
pushl $formatstr # Push string
call scanf # Scan number
pushl $asknrstr2 # Push ask string
call printf # Pop and print ask string
subl $4,%esp # Reserve stack space for int
leal -8(%ebp), %eax # Load address of stack space into %eax
pushl %eax # Push argument of scanf
pushl $formatstr # Push string
call scanf # Scan number
pushl -8(%ebp) # Push number
pushl -4(%ebp) # Push number
pushl $printnrstr # Push print string
call printf # Printf
addl $12,%esp # Move stack pointer
pushl -8(%ebp)
pushl -4(%ebp)
call pow # Call pow subroutine
pushl %eax #
pushl $formatstr # Push string format
call printf # Print
end: movl $0,(%esp) # push program exit code
call exit # exit the program
# ************************************************************************
# * Subroutine : pow *
# * Description : ask user for number and print sum *
# ************************************************************************
pow:
pushl %ebp # Stack base pointer
movl %esp, %ebp # Store stack pointer in %ebp
movl $1,%eax # Store 1 in RESULT
movl 8(%ebp),%ebx # Store 'multiply by' in %ebx
movl 12(%ebp),%ecx # Store COUNT in %ecx
pow2:
cmp $0,%ecx
jle pow3
subl $1,%ecx # Substract 1 from COUNT
mul %ebx # Multiply %eax * %ecx (RESULT * NUMBER)
cmp $0,%ecx # Compare COUNT to 0
jg pow2 # COUNT > 0 = jump to pow2
pow3:
movl %ebp, %esp # Clear local variables from stack
popl %ebp # Restore base pointer
ret