Reputation: 1621
On NASM in Arch Linux, how can I append the character zero ('0') to a 32 bit variable? My reason for wanting to do this is so that I can output the number 10 by setting a single-digit input to 1 and appending a zero. I need to figure out how to append the zero.
The desirable situation:
Please enter a number: 9
10
Using this method, I want to be able to do this:
Please enter a number: 9999999
10000000
How can I do this?
Thanks in advance,
RileyH
Upvotes: 1
Views: 3549
Reputation: 1452
Well, as Bo says... but I was bored. You seem resistant to doing this the easy way (convert your input to a number, add 1, and convert it back to text) so I tried it using characters. This is what I came up with. It's horrid, but "seems to work".
; enter a number and add 1 - the hard way! ; nasm -f elf32 myprog.asm ; ld -o myprog myprog.o -melf_i386 global _start ; you may have these in an ".inc" file sys_exit equ 1 sys_read equ 3 sys_write equ 4 stdin equ 0 stdout equ 1 stderr equ 2 LF equ 10 section .data prompt db "Enter a number - not more than 10 digits - no nondigits.", LF prompt_size equ $ - prompt errmsg db "Idiot human! Follow instructions next time!", LF errmsg_size equ $ - errmsg section .bss buffer resb 16 fakecarry resb 1 section .text _start: nop mov eax, sys_write mov ebx, stdout mov ecx, prompt mov edx, prompt_size int 80h mov eax, sys_read mov ebx, stdin mov ecx, buffer + 1 ; leave a space for an extra digit in front mov edx, 11 int 80h cmp byte [buffer + 1 + eax - 1], LF jz goodinput ; pesky user has tried to overflow us! ; flush the buffer, yell at him, and kick him out! sub esp, 4 ; temporary "buffer" flush: mov eax, sys_read ; ebx still okay mov ecx, esp ; buffer is on the stack mov edx, 1 int 80h cmp byte [ecx], LF jnz flush add esp, 4 ; "free" our "buffer" jmp errexit goodinput: lea esi, [buffer + eax - 1] ; end of input characters mov byte [fakecarry], 1 ; only because we want to add 1 xor edx, edx ; count length as we go next: ; check for valid decimal digit mov al, [esi] cmp al, '0' jb errexit cmp al, '9' ja errexit add al, [fakecarry] ; from previous digit, or first... to add 1 mov byte [fakecarry], 0 ; reset it for next time cmp al, '9' ; still good digit? jna nocarry ; fake a "carry" for next digit mov byte [fakecarry], 1 mov al, '0' cmp esi, buffer + 1 jnz nocarry ; if first digit entered, we're done ; save last digit and add one ('1') into the space we left mov [esi], al inc edx dec esi mov byte [esi], '1' inc edx dec esi jmp done nocarry: mov [esi], al inc edx dec esi cmp esi, buffer jnz next done: inc edx inc edx mov ecx, esi ; should be either buffer + 1, or buffer mov ebx, stdout mov eax, sys_write int 80h xor eax, eax ; claim "no error" exit: mov ebx, eax mov eax, sys_exit int 80h errexit: mov edx, errmsg_size mov ecx, errmsg mov ebx, stderr mov eax, sys_write int 80h mov ebx, -1 jmp exit ;-----------------------------
Is that what you had in mind?
Upvotes: 2