Last active
February 6, 2017 03:22
-
-
Save asmuth/6718995 to your computer and use it in GitHub Desktop.
print (hexa-)decimal numbers in pure x86 assembler (using the OSX/mach system call convention)
This file contains hidden or 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
; compile & run on OSX | |
; $ nasm -f macho -o /tmp/fnord.o fnord.asm | |
; $ ld -o /tmp/fnord /tmp/fnord.o | |
; $ /tmp/fnord | |
section .data | |
section .text | |
global start | |
start: | |
; prints 123 | |
mov eax, 123 | |
mov ebx, 10 | |
call print_number | |
; prints 173 | |
mov eax, 123 | |
mov ebx, 8 | |
call print_number | |
; prints 7B | |
mov eax, 123 | |
mov ebx, 16 | |
call print_number | |
; prints 2A | |
mov eax, 42 | |
mov ebx, 16 | |
call print_number | |
; system call exit(1) with return code 0 | |
mov eax, 0 | |
push eax | |
mov eax, 1 | |
push eax | |
int 0x80 | |
; prints a number to stdout | |
; eax: number | |
; ebx: base (e.g. 10 for decimal or 16 for hex) | |
print_number: | |
; save registers onto stack | |
push eax | |
push ecx | |
push edx | |
; push byte 0 onto the stack | |
sub esp, 1 | |
mov ecx, 0 | |
mov [esp], cl | |
; push byte \n onto the stack | |
sub esp, 1 | |
mov ecx, 10 | |
mov [esp], cl | |
; initialize strlen counter to two (\n\0) | |
mov ecx, 2 | |
next_digit: | |
; increment strlen counter | |
inc ecx | |
; get the next digit to print with modulo | |
mov edx, 0 | |
div ebx | |
; add 48 or 55 (for a-f) to convert number to ascii :) | |
cmp edx, 9 | |
jle is_decimal | |
add edx, 7 | |
is_decimal: | |
add edx, 48 | |
; push this digit onto the stack | |
sub esp, 1 | |
mov [esp], dl | |
; if there is a remainder, loop | |
cmp eax, 0 | |
jne next_digit | |
; put system call params onto stack | |
mov eax, esp | |
push dword ecx | |
push dword eax | |
push dword 1 ; fd: 1 == STDOUT | |
; system call write(4) | |
mov eax, 4 | |
push dword eax | |
int 0x80 | |
; clean up and return | |
add esp, 16 | |
add esp, ecx | |
pop eax | |
pop ecx | |
pop edx | |
ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment