In: Computer Science
Change the following C++ functions to Assembly x86:
int problem1_ ( )
{
int numberArray [3] = {1, -2, 15 };
int result = 0, index = 0;
int numElements = 3;
while (index < numElements)
{
if ( index >= 1 && numberArray[index] > 3 )
{
result += numberArray[index] ;
}
else
{
result -= 3;
}
index++;
}
return result;
}
int problem2_ ( )
{
int a, modulo
int answer = 0, b = 3;
for ( a = 5; a > 0; a-- )
{
if ( ( a % 4 == 0 ) || ( a % 4 == 3) )
{
answer += b ;
}
else
{
answer *= 2;
}
}
return answer;
}
Solution:-
When it comes to code conversion c++ to assembly it is very complicated and time consuming.
problem1_():
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-24], 1
mov DWORD PTR [rbp-20], -2
mov DWORD PTR [rbp-16], 15
mov DWORD PTR [rbp-4], 0
mov DWORD PTR [rbp-8], 0
mov DWORD PTR [rbp-12], 3
.L5:
mov eax, DWORD PTR [rbp-8]
cmp eax, DWORD PTR [rbp-12]
jge .L2
cmp DWORD PTR [rbp-8], 0
jle .L3
mov eax, DWORD PTR [rbp-8]
cdqe
mov eax, DWORD PTR [rbp-24+rax*4]
cmp eax, 3
jle .L3
mov eax, DWORD PTR [rbp-8]
cdqe
mov eax, DWORD PTR [rbp-24+rax*4]
add DWORD PTR [rbp-4], eax
jmp .L4
.L3:
sub DWORD PTR [rbp-4], 3
.L4:
add DWORD PTR [rbp-8], 1
jmp .L5
.L2:
mov eax, DWORD PTR [rbp-4]
pop rbp
ret
problem2_():
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-8], 0
mov DWORD PTR [rbp-12], 3
mov DWORD PTR [rbp-4], 5
.L12:
cmp DWORD PTR [rbp-4], 0
jle .L8
mov eax, DWORD PTR [rbp-4]
and eax, 3
test eax, eax
je .L9
mov eax, DWORD PTR [rbp-4]
cdq
shr edx, 30
add eax, edx
and eax, 3
sub eax, edx
cmp eax, 3
jne .L10
.L9:
mov eax, DWORD PTR [rbp-12]
add DWORD PTR [rbp-8], eax
jmp .L11
.L10:
sal DWORD PTR [rbp-8]
.L11:
sub DWORD PTR [rbp-4], 1
jmp .L12
.L8:
mov eax, DWORD PTR [rbp-8]
pop rbp
ret
Note:- One simple approach that you can use is to write down the c++ code and in the cmd you can call the following command, this command will convert the cpp code to assembly code.
gcc -S programName.cpp