如何打印已使用Assembly读取控制台的字节数?

时间:2015-01-11 17:18:12

标签: linux assembly nasm

这是我的代码( buffer.asm

section .bss
    bufflen equ 2
    buff: resb bufflen

    whatreadlen equ 1
    whatread: resb whatreadlen

section .data

section .text

global main

main:
    nop
    read:
        mov eax,3           ; Specify sys_read
        mov ebx,0           ; Specify standard input
        mov ecx,buff        ; Where to read to...
        mov edx,bufflen     ; How long to read
        int 80h             ; Tell linux to do its magic
        mov esi,eax         ; copy sys_read return value to esi
        mov [whatread],eax  ; Store how many byte reads info to memory at loc whatread

        mov eax,4           ; Specify sys_write
        mov ebx,1           ; Specify standart output
        mov ecx,[whatread]  ; Get the value at loc whatread to ecx
        add ecx,0x30        ; convert digit in EAX to corresponding character digit
        mov edx,1           ; number of bytes to be written
        int 80h             ; Tell linux to do its work

我称之为:

./buffer > output.txt < all.txt

(假设all.txt中有一些文字,如&#34; abcdef&#34;)

我希望在控制台中看到一个数字。但我什么也没看到。我错过了什么?

1 个答案:

答案 0 :(得分:1)

您正在将值传递给sys_write而不是地址,这不会起作用。

改为写下:

main:
    nop
    read:
        mov eax,3           ; Specify sys_read
        mov ebx,0           ; Specify standard input
        mov ecx,buff        ; Where to read to...
        mov edx,bufflen     ; How long to read
        int 80h             ; Tell linux to do its magic
        mov esi,eax         ; copy sys_read return value to esi
        add eax, 30h        ;; Convert number to ASCII digit
        mov [whatread],eax  ; Store how many byte reads info to memory at loc whatread

        mov eax,4           ; Specify sys_write
        mov ebx,1           ; Specify standart output
        lea ecx,[whatread]  ;; Get the address of whatread in ecx
        mov edx,1           ; number of bytes to be written
        int 80h             ; Tell linux to do its work

这里我们将我们(希望是单个数字)的返回值从sys_read转换为ASCII数字,将其存储在whatread,然后告诉sys_write从whatread写入,就好像它是指向一个1个字符的字符串(它是)。

并使用echo aaa | ./buffer > output.txt

进行测试