user1946440
user1946440

Reputation: 359

Trouble with Arithmetic operations in Assembly

I am trying to solve an arithmetic operation which is giving a different output in AT&T assembly program. The arithmetic operation is something like this ((i-(a+b)*(g+c))/((h*e)+(f+j)*d). The values are the following

a: .long 1
b: .long 2
c: .long 3
d: .long 1
e: .long 1
f: .long 1
g: .long 2
h: .long 2
i: .long 20
j: .long 2

According to my calculation the result supposed to be 1. However, I have give the full code below.

.data
intout: .string "Wert %d\n"

a: .long 1
b: .long 2
c: .long 3
d: .long 1
e: .long 1
f: .long 1
g: .long 2
h: .long 2
i: .long 20
j: .long 2

  .text

  .globl main

main:
  movl i, % eax
pushl % eax# i in the stack
movl a, % eax
movl b, % ebx
addl % eax, % ebx# a + b

pushl % ebx#(a + b) in the stack

movl g, % eax
movl c, % ebx
addl % eax, % ebx# g + c

popl % eax# get(a + b)
imull % ebx#(a + b) * (g + c), Result in eax
popl % ebx# get i
subl % ebx, % eax#[i - (a + b) * (g + c)]
pushl % eax#[i - (a + b) * (g + c)] in the stack

movl h, % eax
movl e, % ebx
imul % ebx#(h * e)
pushl % eax#(h * e) in the stack

movl f, % eax
movl j, % ebx
addl % eax, % ebx#(f + j)

movl d, % eax
imul % ebx#(f + j) * d

popl % eax# get(h * e)
addl % eax, % ebx#[(h * e) + (f + j) * d]

popl % eax#[i - (a + b) * (g + c)]
idivl % ebx#[i - (a + b) * (g + c)] / [(h * e) + (f + j) * d]

# Value = "Wert" in % eax given
pushl % eax
pushl $intout
call printf
addl $8, % esp

# Exit
movl $1, % eax
int $0x80

P.S. Please do inform me if I have made any mistakes.

Upvotes: 0

Views: 85

Answers (1)

Lyth
Lyth

Reputation: 2201

First, subl here calculates %eax - %ebx, so it's (a + b) * (g + c) - i.

popl % ebx# get i
subl % ebx, % eax#[i - (a + b) * (g + c)]

You can negate the result to make it right:

negl %eax
pushl % eax#[i - (a + b) * (g + c)] in the stack

Second, imull stores result in %eax, as you commented earlier. So in this code you calculate the result and then "forget" it:

movl d, % eax
imul % ebx#(f + j) * d

popl % eax# get(h * e)

Just change the registers you're working with. (And is it imull, not imul?)

Upvotes: 2

Related Questions