【问题标题】:Iterate through string in memory in Assembly在Assembly中遍历内存中的字符串
【发布时间】:2014-08-26 02:35:02
【问题描述】:

我在Assembly 中依次访问字符串的每个字符时遇到了一些麻烦。在将'Hello World!', 0 声明到bx 注册表之前,我有以下代码调用print_string 例程:

mov bx, HELLO_MSG
call print_string

HELLO_MSG:
  db 'Hello, World!', 0

print_string 内,我可以通过这样做打印字符串的第一个字符:

mov al, [bx]

; Trigger a single character print
mov ah, 0x0e
int 0x10

在我对汇编的基本理解中,第一个字符 (H) 的地址被保存到 bx,所以通过执行 mov al, [bx],我取消引用指针并将 H 的实际值分配给al.

基于这种理解(如果我错了,请纠正我)我尝试了以下方法:

mov cl, bx ; Move the pointer to `cl`
add cl, 1 ; Do pointer arithmetic to add one byte to the address (hopefully referencing the next character)
mov al, [cl] ; Dereference the address

但是我得到这个错误指向mov al, [cl] 行:

error: invalid effective address

我还尝试了以下方法:

mov al, [bx] ; Move the dereferenced address to `al` (so `al` has `H`)
add al, 1 ; Increment `al`, but of course I'm getting the ASCII value of `H` + 1, which is not the next character in the string.

【问题讨论】:

    标签: assembly nasm


    【解决方案1】:

    很多很多年前,有人这样说:
    你想要那个盒子,还是[盒子]里有什么?

    我还尝试了以下方法:

    mov al, [bx] ; Move the dereferenced address to `al` (so `al` has `H`) 
    add al, 1 ; Increment `al`, but of course I'm getting the ASCII value of `H` + 1
    

    CPU 正在按照您的要求执行!

    mov al, [bx]
    

    将 bx 指向的值移动到 al(在您的情况下为 H)

    add al, 1
    

    H 加 1。

    add bx, 1
    mov al, [bx]
    

    现在,al 将包含 E

    或者你可以这样做:

    mov al, [bx + 1]
    

    得到E

    在您的其他代码中,bx 是一个字大小的寄存器(16 位),cl 是一个字节大小的寄存器(8 位),您截断了地址,因此地址无效(当您尝试将 16 位放入 8 位寄存器?)

    这是一个例子:

     HELLO_MSG db 'Hello, World!', 0
     HELLO_LEN equ  $ - HELLO_MSG
    ...
    ...
    ...
        mov     si, HELLO_MSG
        xor     bx, bx
    Next:
        mov     al, byte [si + bx]
        mov     ah, 0x0e
        int     0x10
    
        mov     al, 10
        mov     ah, 0x0e
        int     0x10
    
        inc     bx
        cmp     bx, HELLO_LEN
        jne     Next
    

    输出:

    【讨论】:

    • 感谢您的全面解释!在此之后如何解决问题对我来说很清楚。
    猜你喜欢
    • 2017-05-09
    • 2011-11-14
    • 2011-05-13
    • 1970-01-01
    • 2023-04-07
    • 2018-10-01
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    相关资源
    最近更新 更多