ASM:尝试比较两个整数-我得到了错误的答案 [英] Asm: Trying to compare two integers - I'm getting the WRONG answer
问题描述
我对此很陌生-Ubuntu
+ as
.
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
虽然我希望自己走在正确的道路上,但我对为什么输出"B is hire"感到困惑.比较是否不应该返回正值,因为根据文档, cmp 会将第二个值从第一个值中减去?
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?
感谢对此的支持!
推荐答案
我认为您已经违反了AT&T/Intel
表示法差异.在 Intel 表示法中,源位于最后,例如使用立即值1
加载eax
:
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
在 AT& T 表示法中,其表示为:
In AT&T notation, that would be written as:
movl $1, %eax
按照您的指示进行操作:
Hence your instruction:
cmp %eax, %ebx
给您执行ebx - eax
的结果,而不是您对eax - ebx
的错误假设.它等效于Intel的符号:
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
而且,尽管它与您眼前的问题无关,但此处的正确词是higher
(高于)而不是hire
(为某人使用而付钱).
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).
并且如果使用计算来获取字符串长度,则可以使代码更具可维护性.这样,如果将字符串更改为例如"A is higher\n"
,则无需跟踪并更改硬编码长度10.首先将您的数据更改为:
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.
这篇关于ASM:尝试比较两个整数-我得到了错误的答案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!