【问题标题】:How to create string in loop in x86_64如何在 x86_64 中循环创建字符串
【发布时间】:2021-07-24 11:56:48
【问题描述】:

我有一个字符串,我想将该字符串中的任何符号转换为另一个符号(例如,“a”转换为“4”,“e”转换为“3”等)。

逻辑:

i) 使用db定义的字符串变量

ii) 使用resb 定义的字符串变量将转换后的字符传输到

iii) 循环遍历第一个字符串并根据需要使用cmp 转换字符

iv) while 循环将转换后的字符存储在第二个变量中

v) 打印第二个转换后的字符串

我目前的尝试:

section .data
    ; constants
    EXIT_SUCCESS    equ 0
    SYS_exit    equ 60
    SYS_read    equ 0
    SYS_write   equ 1

    ; variables
    sym     db "01010",10,"$"
    text0   db " "
    text1   db "$"
    text2   db "",10
    
section .bss
    ; reserve space for output symbol
    symbol  resb 6

section .text
    global _start

_start:
    mov rax, sym
    call _print

    mov rax, SYS_exit
    mov rdi, EXIT_SUCCESS
    syscall


_print:
    mov rbx, 0          ; use rbx to count len(string)

_printLoop:
    inc rax
    inc rbx
    mov cl, [rax]       ; will hold next char in string
    
    cmp cl, "0"         ; if 0 add space
    je _addT0

    cmp cl, "1"         ; if 1 add $ symbol
    je _addT1

    cmp cl, "$"         ; if end of string
    je _continuePrint

    mov symbol[rbx], text3      ; default: add new line 
    jmp _printLoop

_addT0:
    mov symbol[rbx], text0
    jmp _printLoop

_addT1:
    mov symbol[rbx], text1
    jmp _printLoop

_continuePrint:
    mov rax, 1
    mov rdi, 1
    mov rsi, symbol
    mov rdx, rbx            ; use rbx as count
    syscall

    ret

例如,如果 sym"01010",我希望输出 sym 等于 " $ $ "

【问题讨论】:

  • mov symbol[rbx], text0 复制地址而不是值。
  • _printLoop: 处递增rax 使您始终省略输入字符串的第一个字符。而不是text0 db " " 使用text0 equ " ";类似text1 equ "$"text2 equ 10。正确的 NASM 语法是 mov byte [symbol+rbx], text2 ; default: add new line
  • @vitsoft 谢谢,我怎么能不省略输入字符串的第一个字符?请考虑将您的评论作为答案

标签: linux assembly x86-64


【解决方案1】:

_printLoop: 处递增rax 使您始终忽略输入字符串的第一个字符。在使用来自eax 的地址之后,将增量推迟到以后:

_printLoop:
    inc rbx
    mov cl, [rax]       ; will hold next char in string
    inc rax             ; Prepare EAX to point at the next character.
    ...

mov symbol[rbx], text0 这样的指令是错误的,因为text0 代表的是text0地址,而不是它的内容
text0 db " " 重新定义为text0 equ " ",这将使它成为一个(立即数" " 别名0x20)而不是内存变量。与text1 equ "$"text2 equ 10 类似。 那么正确的 NASM 语法是
mov byte [symbol+rbx], text2 ; default: add new line.

【讨论】:

  • 非常感谢 - 非常有帮助。请问为什么是[symbol+rbx]?或者这只是所需的语法?
  • @Dean 方括号 [] 在大多数汇编程序中造成 [memory_contents]immediate_value 之间的区别。另请参阅memory address syntax
猜你喜欢
  • 2015-06-26
  • 1970-01-01
  • 2022-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-08
  • 1970-01-01
相关资源
最近更新 更多