In: Computer Science
I want to convert those codes to assembler code
// Problem 1
// for loop
J=5
for(i=1; i<5; i++) {
j--
}
// Problem 2
// if - then - else
i=4
if (i < 5) then
j = 3
else
j = 2
// Problem 3
//while loop
i = 0
j = 0
while(i==0) {
j++
if j = 5 then
i = j
}
1) Simply we write mov instruction for assigning values to a variable.
Mov instruction : mov destination,source.
Given problem :
//for loop
j=5
for(i=1; i<5; i++) {
j--
}
Given code can be converted to assembley code as follows :
pushq %rbp
movq %rsp, %rbp
movl $5, -8(%rbp) ;j=5
movl $1, -4(%rbp) ;i=1
jmp .L2
.L3:
subl $1, -8(%rbp)
addl $1, -4(%rbp)
.L2:
cmpl $4, -4(%rbp) ;condition
check - i<5
jle .L3
popq %rbp
ret
2) Given problem :
i=4
if (i < 5) then
j = 3
else
j = 2
This code can be converted to assembley code as follows :
pushq %rbp
movq %rsp, %rbp
movl $4, -8(%rbp) ;assignment
instruction which is equivalent to i =4i=4
cmpl $4, -8(%rbp) ;comparing
whether i < 5 or not
jg .L2
movl $3, -4(%rbp)
jmp .L3
.L2:
movl $2, -4(%rbp)
.L3:
popq %rbp
ret
3) Given code :
i = 0
j = 0
while(i==0) {
j++
if j = 5 then
i = j
}
Above code can be converted to assembley code as follows :
pushq %rbp
movq %rsp, %rbp
movl $0, -8(%rbp)
movl $0, -4(%rbp)
jmp .L2
.L3:
addl $1, -4(%rbp) ;increment of j
cmpl $5, -4(%rbp)
jne .L2
movl -4(%rbp), %eax
movl %eax, -8(%rbp)
.L2:
cmpl $0, -8(%rbp) ;while condition
check
je .L3
popq %rbp
ret