Skip to content

Instantly share code, notes, and snippets.

@alu96
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alu96/9743404 to your computer and use it in GitHub Desktop.
Save alu96/9743404 to your computer and use it in GitHub Desktop.
Assembler program to calculate the digit sum of a number
/***********************************************
Author : alu96
Date : 17.03.2014
Description : This small assembler programm calculates and prints out the digit sum of a number. (123 will result in 6)
**********************************************/
.globl _main # main entry point
_main:
pushl %ebp
movl %esp, %ebp
pushl %eax
pushl $message_begin
calll _printf # print stirng message_begin
addl $8, %esp # cleanup stack
push $number # parameter 2: pointer to number
push $format # parameter 1: format
call _scanf # read number from console
addl $8, %esp # cleanup stack
movl (number), %eax # write number to temp
movl %eax, (temp) #
digitsum_calc:
cmpl $0, (temp) # check if temp is 0
je end # if yes, jump to end
movl $0, %edx
movl (temp), %eax
movl $10, %ecx
idivl %ecx # %edx:%eax / %ecx --> %eax; remainder: %edx
movl %eax, (temp) # save result in temp
movl (digitsum), %eax # load digit sum in %eax
addl %edx, (digitsum) # add remainder of division to the digit sum
jmp digitsum_calc
end:
pushl digitsum
pushl number
pushl $message_end
calll _printf # print string message_end
addl $12, %esp # cleanup stack
xorl %eax, %eax # reset %eax
popl %ebp
ret
.data
number: .int 0
digitsum: .int 0
temp: .int 0
format: .asciz "%i"
message_end: .asciz "The digit sum of %i is %i\n"
message_begin: .asciz "Number:"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment