【问题标题】:Remove Trailing Line-Breaking Characters from Read Input in Assembly从汇编中的读取输入中删除尾随换行符
【发布时间】:2012-05-03 12:15:19
【问题描述】:

我最近一直在自学汇编,我认为 NASM 汇编器及其语法是最有效和最容易使用的。我目前正在使用标准输入和输出;但是,我不知所措,因为我需要从正在阅读的字符串中删除换行符(回车符、换页符、换行符、- 0xd、0xc 和 0xa)。考虑以下几点:

    section .data
;; ...
    section .bss
input:  resb    255
 .len:  equ     $ - input

    section .text
    global  _start

_start:
    ;; Display message prompting for input, then...
    mov     edx, input.len
    mov     ecx, input
    mov     ebx, 0
    mov     eax, 3
    int     0x80

目前,我希望去除尾随的换行符。考虑以下伪代码:

if the last character in `input` is 0xa or 0xc or 0xd:
    subtract the last character from `input`
repeat until false

我很可能已经说清楚了,但这里有一个 Python 等价于上面的伪代码:

while input[-1] is "\r" or input[-1] is "\f" or input[-1] is "\n":
    input = input[:-1]

【问题讨论】:

  • 我正在尝试设计一个子程序来删除字符串的最后一个字符,如果该字符是回车符、换页符或换行符;它将循环直到所述条件为假。

标签: string assembly stdin nasm


【解决方案1】:

这不是特别优雅或高效,但它可以提供一个起点:

jcomeau@intrepid:/tmp$ cat test.nasm ; nasm -f elf -o test.o test.nasm; ld -o test test.o; ./test
    section .bss
input:  resb    255
 .len:  equ     $ - input

    section .text
    global  _start

_start:
    ;; Display message prompting for input, then...
    mov     edx, input.len
    mov     ecx, input
    mov     ebx, 0
    mov     eax, 3
    int     0x80  ;read in from stdin
    call    rstrip
    mov     edx, eax  ;count
    mov     ebx, 1  ;stdout
    mov     eax, 4
    int     0x80  ;write out
    mov     eax, 1
    xor     ebx, ebx
    int     0x80
rstrip:
    dec     eax  ;convert 1-based length to 0-based pointer
.loop:
    cmp     byte [ecx + eax], 0xa
    je      .chop
    cmp     byte [ecx + eax], 0xc
    je      .chop
    cmp     byte [ecx + eax], 0xd
    je      .chop
.done:
    inc     eax  ;convert pointer back to length
    ret
.chop:
    mov     byte [ecx + eax], 0
    dec     eax
    jns     .loop
    jmp     .done
this is a test
this is a testjcomeau@intrepid:/tmp$

【讨论】:

  • 谢谢!有趣的方法...我对此真的很陌生。
猜你喜欢
  • 2022-01-05
相关资源
最近更新 更多