PROWAREtech
x86 Assembly: itoa Procedure
int to ASCII string - Convert Numbers to Strings.
Use MASM for Visual C++ Express Edition 2005 to compile this procedure.
Use the itoa_asm
procedure to convert an integer to a C-string. To convert a C-string to an integer, use atoi_asm
(ASCII to int).
TITLE 'extern "C" void itoa_asm(int val, char *sz, unsigned radix);'
.386P
.model FLAT
PUBLIC _itoa_asm
_TEXT SEGMENT
_itoa_asm PROC NEAR
mov ecx, DWORD PTR [esp+8] ; sz
push ebx
push ebp
; if radix equals 10 and val is a negative number
mov ebp, DWORD PTR [esp+20] ; radix
cmp ebp, 10
push esi
mov esi, DWORD PTR [esp+16] ; val
push edi
jne SHORT label1
test esi, esi
jge SHORT label1
mov BYTE PTR [ecx], 45 ; '-'
inc ecx
neg esi
label1:
mov edi, ecx
label2:
xor edx, edx
mov eax, esi
div ebp
mov eax, esi
mov ebx, edx
xor edx, edx
div ebp
cmp ebx, 9
mov esi, eax
jbe SHORT label3
add bl, 55 ; 'A' - 10
jmp SHORT label4
label3:
add bl, 48 ; '0'
label4:
mov BYTE PTR [ecx], bl
inc ecx
test esi, esi
ja SHORT label2
; terminate string
mov BYTE PTR [ecx], 0
dec ecx
label5:
; reverse string
mov dl, BYTE PTR [edi]
mov al, BYTE PTR [ecx]
mov BYTE PTR [ecx], dl
dec ecx
mov BYTE PTR [edi], al
inc edi
cmp edi, ecx
jb SHORT label5
pop edi
pop esi
pop ebp
pop ebx
ret 0
_itoa_asm ENDP
_TEXT ENDS
END
Use the uitoa_asm
procedure to convert an unsigned integer to a C-string. To convert a C-string to a positive number, use atoui_asm
(ASCII to uint).
TITLE 'extern "C" void uitoa_asm(unsigned int val, char *sz, unsigned radix);'
.386P
.model FLAT
PUBLIC _uitoa_asm
_TEXT SEGMENT
_uitoa_asm PROC NEAR
push ebx
push ebp
mov ebp, DWORD PTR [esp+20] ; radix
push esi
mov esi, DWORD PTR [esp+20] ; sz
push edi
mov edi, DWORD PTR [esp+20] ; val
mov ebx, esi
label1:
xor edx, edx
mov eax, edi
div ebp
mov eax, edi
mov ecx, edx
xor edx, edx
div ebp
cmp ecx, 9
mov edi, eax
jbe SHORT label2
add cl, 55 ; 'A' - 10
jmp SHORT label3
label2:
add cl, 48 ; '0'
label3:
mov BYTE PTR [esi], cl
inc esi
test edi, edi
ja SHORT label1
; terminate string
mov BYTE PTR [esi], 0
dec esi
label4:
; reverse string
mov cl, BYTE PTR [ebx]
mov al, BYTE PTR [esi]
mov BYTE PTR [esi], cl
dec esi
mov BYTE PTR [ebx], al
inc ebx
cmp ebx, esi
jb SHORT label4
pop edi
pop esi
pop ebp
pop ebx
ret 0
_uitoa_asm ENDP
_TEXT ENDS
END
Comment