Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assembly language using shl to multiply by an odd number?

Tags:

x86

assembly

I need to multiply EAX by 37, I know I can use shl eax,5 and shl register,2 then add the register to eax to multiply by 38, but I'm not sure the code to multiply by an odd number and I have to use shl add and mov only. Thanks!

like image 395
user2990286 Avatar asked Nov 22 '13 17:11

user2990286


2 Answers

Besides what harold has told you, you can use the LEA instruction to perform multiplications as well:

EAX * 2 :  lea eax,[eax*2]
EAX * 3 :  lea eax,[eax*2+eax]
EAX * 4 :  lea eax,[eax*4]
EAX * 5 :  lea eax,[eax*4+eax]
EAX * 8 :  lea eax,[eax*8]
EAX * 9 :  lea eax,[eax*8+eax]
like image 21
mcleod_ideafix Avatar answered Nov 10 '22 22:11

mcleod_ideafix


Using LEA, you can directly multiply by a lot of small, odd constants (2,4,8,3,5,9) as well as add two registers and move the answer to a different place. This is astonishingly useful. Composing these, you can multiply by pretty much any small constant using a sequence of LEA instructions, often pretty short. Judicious use of other ADD, SHL, and SUB (including NEG then ADD) instructions can shorten those sequences. Such short sequences of these are almost always faster than using multiply, partly because many of the instructions are overlapped in execution by current processors:

Multiply eax by 37:

 lea ecx, [eax+8*eax] ; 9 * eax
 lea eax, [ecx*4+eax] ; 37 * eax

Multiply eax by 38:

 lea ecx, [8*eax]
 neg eax
 lea ecx, [5*ecx] 
 lea eax, [ecx+2*eax]

Better:

 lea ecx, [8*eax+eax] ; 9 * eax
 lea ecx, [4*ecx] ; 36 * eax
 lea eax, [eax*2+ecx] ; 38 * eax

Just for fun, multiply by 103:

 lea ecx, [8*eax] ; 8 * eax
 lea ecx, [ecx*4] ; 32 * eax
 lea ecx, [ecx*2+ecx] ; 96 * eax
 lea ecx, [ecx+8*eax]; ; 104 * eax
 sub ecx, eax ; 103 * eax
like image 84
Ira Baxter Avatar answered Nov 10 '22 21:11

Ira Baxter