Question

This is the codes i am trying to convert

int sum(int n) {
  if(n<=1) 
    return n;
  else
    return n+sum(n-1);
}

I need help converting the c+ code to machine language

i assume you use an add 
4000000000        to initialize eax to 0 which would be n
and jump greater equal would be 
7500000001

i am lost when it comes to the function part:

Was it helpful?

Solution

If you compile your snippet with:

g++ -g -c filename.cpp

GCC will produce an unlinked (-c) object file with debugging information (-g) called filename.o. If you then run

objdump -d -M intel -S filename.o

It will output a nice display of the dissasembly + machine code for the file, like this:

machine-code.o:     file format elf64-x86-64


Disassembly of section .text:

0000000000000000 <_Z3sumi>:
int sum(int n) {
   0:   55                      push   rbp
   1:   48 89 e5                mov    rbp,rsp
   4:   48 83 ec 10             sub    rsp,0x10
   8:   89 7d fc                mov    DWORD PTR [rbp-0x4],edi
  if(n<=1)
   b:   83 7d fc 01             cmp    DWORD PTR [rbp-0x4],0x1
   f:   7f 05                   jg     16 <_Z3sumi+0x16>
    return n;
  11:   8b 45 fc                mov    eax,DWORD PTR [rbp-0x4]
  14:   eb 10                   jmp    26 <_Z3sumi+0x26>
  else
    return n+sum(n-1);
  16:   8b 45 fc                mov    eax,DWORD PTR [rbp-0x4]
  19:   83 e8 01                sub    eax,0x1
  1c:   89 c7                   mov    edi,eax
  1e:   e8 00 00 00 00          call   23 <_Z3sumi+0x23>
  23:   03 45 fc                add    eax,DWORD PTR [rbp-0x4]
}
  26:   c9                      leave
  27:   c3                      ret

Which may be of some use to you. In this case, the machine code it produced seems to be:

554889e54883ec10897dfc837dfc017f058b45fceb108b45fc83e80189c7e8000000000345fcc9c3
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top