c - intro to x86 assembly -
i'm looking on example on assembly in csapp (computer systems - programmer's perspective 2nd) , want know if understanding of assembly code correct.
practice problem 3.23
int fun_b(unsigned x) { int val = 0; int i; ( ____;_____;_____) { } return val; }
the gcc c compiler generates following assembly code:
x @ %ebp+8 // i've gotten far 1 movl 8(%ebp), %ebx // ebx: x 2 movl $0, %eax // eax: val, set 0 since eax return // value stored , val being returned @ end 3 movl $0, %ecx // ecx: i, set 0 4 .l13: // loop 5 leal (%eax,%eax), %edx // edx = val+val 6 movl %ebx, %eax // val = x (?) 7 andl $1, %eax // x = x & 1 8 orl %edx, %eax // x = (val+val) | (x & 1) 9 shrl %ebx shift right 1 // x = x >> 1 10 addl $1, %ecx // i++ 11 cmpl $32, %ecx // if < 32 jump loop 12 jne .l13
there similar post on same problem solution, i'm looking more of walk-through , explanation of assembly code line line.
you seem have meaning of instructions figured out. comment on lines 7-8
wrong however, because assign eax
val
not x
:
7 andl $1, %eax // val = val & 1 = x & 1 8 orl %edx, %eax // val = (val+val) | (x & 1)
putting c template be:
for(i = 0; < 32; i++, x >>= 1) { val = (val + val) | (x & 1); }
note (val + val)
left shift, function doing shifting out bits x
on right , shifting them in val
right. such, it's mirroring bits.
ps: if body of for
must empty can of course merge third expression.
Comments
Post a Comment