Comparing variables in NASM Assembly

僤鯓⒐⒋嵵緔 提交于 2021-01-28 07:36:27

问题


Serious trouble trying to get this working .. just starting NASM assembly so sorry if this is a noob of an issue, but any help is appreciated thankyou!

Trying to get the two variables to render equal so the jump after cmp works. This is frustrating me greatly, as the direct values ( if a mov eax and ebx to be "5" ) it works so is it an address problem? I'm not sure.

section .data

    str_equal   db      "Equal!", 0xA
    len_equal   equ     $ - str_equal

    str_number_a    db      "5"
    str_number_b    db      "5"

section .text

    global _start

_start:

    mov     eax,        [ str_number_a ]
    mov     ebx,        [ str_number_b ]

    cmp     eax,        ebx
    je      _Equal
    jmp     _Exit

ret


_Equal:

    mov     eax,        4                       ; syscall - write()
    mov     ebx,        1                       ; stdout
    mov     ecx,        str_equal
    mov     edx,        len_equal
    int     0x80                                ; Call dat Kernel

    jmp     _Exit

ret


_Exit:

    mov     eax,        1
    mov     ebx,        0
    int     0x80

ret

回答1:


The problem is that you are filling 32-bit registers with 32-bits of data when attempting to move the single byte from the strings into registers:

mov    eax,    [ str_number_a ]
mov    ebx,    [ str_number_b ]

If we have a look at the memory, there could be anything beyond the first byte of the strings:

xx xx xx 35 1F 4A 59 xx xx xx
         ^   ^^^^^^^
         '5' Garbage

As eax and ebx are 32-bit registers, they read in both the character '5' and the garbage following. What does this mean? The since the garbage memory beyond the character '5' in both strings are very likely to be different, the comparison between eax and ebx will always be non-equal.

This can be fixed by changing the 32-bit/4 byte comparison (cmp) to an 8-bit/1 byte (or, single character) comparison:

cmp     byte eax, ebx

This way, only the first byte of each register will be compared.

EDIT:

Alternatively, you could use 8-bit registers to store data:

mov    al, [ str_number_a ]
mov    ah, [ str_number_b ]

cmp    al, ah


来源:https://stackoverflow.com/questions/32774374/comparing-variables-in-nasm-assembly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!