Last active
June 17, 2016 16:49
-
-
Save sethmclean/3d4f1a05b7c1509c5b08 to your computer and use it in GitHub Desktop.
100 to 1... in x86-64 ASM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DEFAULT REL | |
%define SYSCALL_WRITE 0x2000004 | |
%define SYSCALL_EXIT 0x2000001 | |
section .data | |
section .bss | |
section .text | |
global start | |
start: | |
mov rax, 100 ; starting with 100 | |
dec_loop: | |
call display_str ; display our current value | |
dec rax ; decrement | |
cmp rax,0 | |
jg dec_loop ; loop the display | |
mov rax, SYSCALL_EXIT | |
mov rdi, 0 | |
syscall ; Terminate | |
display_str: | |
push rax ; store the value to the stack | |
mov rbx, 0 ; init our character count | |
push 0xA ; push a new line | |
inc rbx ; count the new line. | |
reg_to_disp: | |
inc rbx ; we're adding a character, increment | |
push rbx ; store temporarily | |
mov rbx, 10 ; We're writing out in base 10 | |
mov rdx, 0 ; set to 0, otherwise div will segfault (?!) | |
div rbx ; divide rax, store remainder in rdx | |
pop rbx ; retrieve our char count. | |
or rdx, 0x30 ; OR 0x30 to our remainder, so it's the ASCII digit | |
push rdx ; push it to the stack | |
cmp rax, 0 | |
jg reg_to_disp ; if rax isn't 0, loop because we have more conversion | |
push rsp | |
mov rax, rbx ; move char count to rax | |
mov rbx, 8 ; set rbx to wordsize | |
mul rbx ; multiply by wordsize to get bitcount | |
mov rbx, rax ; move the result back to rbx. | |
mov rdi, 1 ; print to stdout | |
mov rsi, [rsp] ; point rsi to the stack pointer location | |
mov rdx, rbx ; set rdx to the number of bits to print | |
mov rax, SYSCALL_WRITE ; we're writing out | |
syscall ; DO IT | |
add rsp, rbx ; reset our stack pointer | |
add rsp, 8 ; one more word for the rsp pointer pushed. | |
pop rax ; retrieve rax from the stack | |
ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment