All pastes #954116 Raw Edit

Mine

public text v1 · immutable
#954116 ·published 2008-03-23 17:56 UTC
rendered paste body
; Fills specified buffer with the string representation of an integer value.
; This works just like the C function itoa, but with the exception of being
; fixed to a radix of 10.
;
; Parameters:
;	- Value						[ebp+8]
;	- Buffer					[ebp+12]

itoa:

	push	ebp
	mov		ebp, esp

	mov		ecx, [ebp+12]		; Buffer address goes in ecx.

	xor		edx, edx
	mov		eax, [ebp+8]		; Value goes in eax.
	mov		ebx, 10
	div		ebx					; Divide value by 10.

.loop

	push	ebx					; Store old decimal on the stack.
	push	edx					; Store old value on the stack

	add		edx, 0x30			; Add offsset of ascii zer0.
	mov		eax, edx			; Move ascii value to eax.

	mov		edx, [ecx]			; Buffer goes in edx.
	mov		edi, edx
	
	stosb						; Store a byte.

	mov		eax, 10				; Time to multiply!
	mul		ebx					; eax is now ten times larger than ebx!

	mov		ebx, eax			; Set ebx to new decimal.

	xor		edx, edx
	mov		eax, [ebp+8]		; Value in eax.
	div		ebx					; Divide by current decimal in ebx, the remainder is used in edx.

	pop		eax					; Pop old value to eax.
	sub		edx, eax			; Subtract new value by old one.

	pop		eax					; Pop old decimal to eax.
	push	ebx					; Push current decimal.
	mov		ebx, edx			; Subtracted value goes in ebx.

	push	ebx					; Push edx onto stack.
	push	eax					; Push eax onto stack.
	pop		ebx					; Pop eax to ebx.
	pop		eax					; Pop ebx to eax.

	xor		edx, edx
	div		ebx					; Divide value in eax by old decimal.
	
	inc		ecx					; Move to next character

	pop		ebx					; Get back decimal from stack and put in ebx.
	hlt
	cmp		eax, 0				; See if this is the end.
	jne		.loop

	mov		edi, [ecx]
	xor		eax, eax			; Null terminate.
	stosb						; Store null.

	mov		eax, [ebp+12]		; Set return value to buffer address.

	leave
	ret