1

在 Arch Linux 的 NASM 上,如何将字符零 ('0') 附加到 32 位变量?我想要这样做的原因是,我可以通过将一位输入设置为 1 并附加一个零来输出数字 10。我需要弄清楚如何附加零。

理想的情况:

Please enter a number: 9
10

使用这种方法,我希望能够做到这一点:

Please enter a number: 9999999
10000000

我怎样才能做到这一点?

提前致谢,

莱利

4

1 回答 1

2

好吧,正如博所说……但我很无聊。您似乎拒绝以简单的方式执行此操作(将您的输入转换为数字,加 1,然后将其转换回文本)所以我尝试使用字符。这就是我想出的。这很可怕,但“似乎有效”。

; 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
;-----------------------------    

你是这么想的吗?

于 2012-11-10T14:41:04.140 回答