简体   繁体   中英

Assembly code to C practice

在此输入图像描述

So I was doing the following problem, making the assembly code to C(still kind of new to assembly code) Suppose you know that when a function with prototype long decode4(long x, long y, long z) is compiled into assembly code, the body of the code is as follows

addq %rsi, %rdi
imulq %rdx, %rdi    
movq %rdi, %rax    
sarq $15, %rax    
salq $31, %rax    
andq %rdi, %rax    
ret

Parameters x, y, and z are passed in registers %rdi, %rsi, and %rdx. The code stores the return value in register %rax.

How I interpreted the code was with the following:

long w =(x+y)*z;
w=(w>>15);
w=(<<31);
return x&w;

please review my code, and please be nice!

Yes your interpretation is right. Just to add. The code could also be -

addq %rsi, %rdi   => x = x + y
imulq %rdx, %rdi  => x = x*z
movq %rdi, %rax   => w = x
sarq $15, %rax    => w = w >> 15
salq $31, %rax    => w = w << 31
andq %rdi, %rax   => w = w & x
ret               => return w

+++++++++++++++++++++++++++++++++++++++++++++++++

long w;
x=(x+y)*z; 
w=((x>>15)<<31); 
return x&w;  

It all depends how the compiler decides to translate it to asm, sometimes adding its own optimization. You can't convert it exactly to the C code originally if you want.

But you can do the reverse. generate an asm file from the C file.

gcc -O2 -S -c file.c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM