在Assembly中迭代内存中的字符串

时间:2014-08-26 02:35:03

标签: assembly nasm

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

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.

1 个答案:

答案 0 :(得分:3)

许多年前,有人这样说过:
你想要这个盒子,还是[盒子里]的内容?

  

我也尝试了以下内容:

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

输出:

enter image description here

相关问题