Last active
January 2, 2024 12:13
-
-
Save tnewman/63b64284196301c4569f750a08ef52b2 to your computer and use it in GitHub Desktop.
atoi in Assembly - Convert a number string to a 64 bit integer.
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
global atoi | |
section .text | |
atoi: | |
mov rax, 0 ; Set initial total to 0 | |
convert: | |
movzx rsi, byte [rdi] ; Get the current character | |
test rsi, rsi ; Check for \0 | |
je done | |
cmp rsi, 48 ; Anything less than 0 is invalid | |
jl error | |
cmp rsi, 57 ; Anything greater than 9 is invalid | |
jg error | |
sub rsi, 48 ; Convert from ASCII to decimal | |
imul rax, 10 ; Multiply total by 10 | |
add rax, rsi ; Add current digit to total | |
inc rdi ; Get the address of the next character | |
jmp convert | |
error: | |
mov rax, -1 ; Return -1 on error | |
done: | |
ret ; Return total or error code |
Negative numbers are not supported in this snippet. You'd have to check for a leading - and negate the final result if negative.
That's what I did, thx
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Negative numbers are not supported in this snippet. You'd have to check for a leading - and negate the final result if negative.