itsols
itsols

Reputation: 5582

Asm: Trying to compare two integers - I'm getting the WRONG answer

I'm quite new to this - Ubuntu + as.

I'm trying to do a simple comparison between two integers and show a message. Here's my code:

.data
    MsgA:   .ascii "A is higher\n"
    MsgB:   .ascii "B is higher\n"
.text

.global _start

_start:

    movl $25, %eax
    movl $15, %ebx
    cmp %eax, %ebx      #Compare the two (eax - ebx)
    jg AHire        #If result is bigger, A Hire

    #say that B is hire 
    movl $4, %eax
    movl $1, %ebx
    movl $MsgB, %ecx    #Otherwise B Hire
    movl $10, %edx
    int $0x80

    jmp EndProg

#say that A is hire
AHire:  
    movl $4, %eax
    movl $1, %ebx
    movl $MsgA, %ecx
    movl $10, %edx
    int $0x80

EndProg:
    movl $1, %eax
    movl $0, %ebx
    int $0x80

While I hope I'm on the right track, I am kind of puzzled as to why the output is "B is hire". Shouldn't the comparison return a positive value since according to the docs, cmp does a subtraction of the 2nd value from the 1st?

Thanks for any support on this!

Upvotes: 0

Views: 105

Answers (1)

paxdiablo
paxdiablo

Reputation: 881403

I think you've fallen afoul of the AT&T/Intel notation differences. In Intel notation, the source comes last, such as with loading eax with the immediate value 1:

mov eax, 1

In AT&T notation, that would be written as:

movl $1, %eax

Hence your instruction:

cmp %eax, %ebx

gives you the result of performing ebx - eax, not your erroneous assumption of eax - ebx. It's equivalent to the Intel notation of:

cmp ebx, eax

And, though it's irrelevant to your problem at hand, the correct word here is higher (more high than) rather than hire (pay someone for the use of something).

And you can possibly make your code more maintainable if you use calculation to get the string lengths. That way, if you change the strings to, for example, "A is higher\n", you won't need to track down and change the hard-coded length of ten as well. First change your data to:

.data
    MsgA:   .ascii "A is hire\n"
    MsgB:   .ascii "B is hire\n"
    MsgC:

Then change the code that loads up the length to one of:

    movl MsgB-MsgA, %edx  ; for printing MsgA
    movl MsgC-MsgB, %edx  ; for printing MsgB

That calculates the length using actual labels so that it will auto-magically adjust to a different string size.

Upvotes: 1

Related Questions