【问题标题】:Conditional Jumps not Working as Intended in NASM条件跳转未按 NASM 的预期工作
【发布时间】:2020-07-16 14:30:39
【问题描述】:

我正在尝试编写一个执行以下操作的程序:

  1. bx 寄存器中存储一个整数
  2. 如果bx寄存器中存储的值小于等于4,则将A复制到al寄存器中
  3. 如果bx寄存器中存储的值大于10,则将B复制到al寄存器中
  4. 如果这两个条件都不成立,请将C 复制到al 寄存器中
  5. 输出al寄存器的值

这是我写的程序:

section .data

section .text
    global _start
    
    _start:
        mov bx, 2
        
        cmp bx, 4
        jle copy_a
        cmp bx, 10
        jg copy_b
        mov al, 'C'
        
        copy_a:
            mov al, 'A'
            
        copy_b:
            mov al, 'B'
            
        mov byte [esp], al   ;push al
        mov eax, 0x04
        mov ebx, 0x01
        mov ecx, esp         ;esp points to the character to be printed
        mov edx, 0x01
        int 0x80
            
        mov eax, 0x01
        mov ebx, 0x00
        int 0x80

无论我将bx 的值更改为什么,它总是输出B

【问题讨论】:

  • mov byte [esp], al 不会推送,它只会覆盖堆栈内存中的内容。没关系,但是您的 cmets 与代码不匹配。如果你想推送,你会push eax(AL 是 EAX 的低字节,x86 是小端,所以 ESP 会指向来自 AL 的字节)

标签: assembly x86 nasm


【解决方案1】:

你必须添加一个跳转:

section .text
    global _start
    
    _start:
        mov bx, 2
        
        cmp bx, 4
        jle copy_a
        cmp bx, 10
        jg copy_b
        mov al, 'C'
        
        copy_a:
            mov al, 'A'
            jmp continue
        copy_b:
            mov al, 'B'

        continue:     
            mov byte [esp], al   ;push al
            mov eax, 0x04
            mov ebx, 0x01
            mov ecx, esp         ;esp points to the character to be printed
            mov edx, 0x01
            int 0x80    
            mov eax, 0x01
            mov ebx, 0x00
            int 0x80

你必须添加这个跳转,否则,处理器只会看到:

mov al, 'A'
mov al, 'B'

处理器将首先将'A' 移动到al,然后是'B''。这导致al 始终为B

此外,如果没有任何条件为真,您忘记添加移动。 (bx > 4 && bx <= 10) 编辑: 要添加第三个条件,请尝试以下操作:

section .text
    global _start
    
    _start:
        mov bx, 2
        
        cmp bx, 4
        jle copy_a
        cmp bx, 10
        jg copy_b
        mov al, 'C'
        jmp continue ;Here.
        copy_a:
            mov al, 'A'
            jmp continue
        copy_b:
            mov al, 'B'

        continue:     
            mov byte [esp], al   ;push al
            mov eax, 0x04
            mov ebx, 0x01
            mov ecx, esp         ;esp points to the character to be printed
            mov edx, 0x01
            int 0x80    
            mov eax, 0x01
            mov ebx, 0x00
            int 0x80

【讨论】:

  • 感谢您的回复;我运行了你提供的代码,看起来你是对的,“C”永远不会存储在“al”中,即使我在两次跳转后写了“mov al,'C'”。我该如何解决?
猜你喜欢
  • 1970-01-01
  • 2021-12-13
  • 2015-04-21
  • 1970-01-01
  • 1970-01-01
  • 2016-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多