Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Dividing by power of 2

shaolin007shaolin007 Member Posts: 1,018
Sigh, can't figure this one out to save the life of me, lol. I have several years x86 assembler experience but I haven't done any programming in a few years so I am literally almost starting from scratch again. I am teaching my brother assembler and he is a total beginner so we are both learning at the same time.

Anyway, know how to multiply by a power of 2 if the number is even using shl instruction.

10 = shift 3 + shift 1

I am stumped on how to do it with division. Someone want to chime in?

Comments

  • anthrax11anthrax11 Member Posts: 511
    I'm not sure where to begin :P
    Maybe these basic examples will help:
    [code]
    shl eax, 1 ; multiply eax by 2
    shl eax, 2 ; multiply by 4
    shl eax, n ; multiply by 2^n
    [/code]
    When doing division, just shift to the right instead of the left:
    [code]
    shr eax, 1 ; divide by 2
    shr eax, 2 ; divide by 4
    shr eax, n ; divide by 2^n
    [/code]
    I'm pretty sure mul and div aren't as slow as they used to be, so those can be used, of course:
    [code]
    mul ebx ; multiply eax by ebx - result in eax:edx
    div ebx ; divide eax:edx by ebx - remainder in edx, quotinent in eax
    [/code]
    A related trick is to use lea (Load Effective Address) to multiply by small numbers:
    [code]
    lea ebx, [ebx + ebx*2] ; multiply ebx by 3
    lea ebx, [ebx + ebx*8] ; multiply ebx by 9
    [/code]
    I also remembered an interesting program that converts division by a constant into a series of mul/shr/inc instructions. It's the program called MagicNumber:
    http://win32assembly.online.fr/source.html

    I'm not sure if this is what you were expecting, but I hope it helps!
  • shaolin007shaolin007 Member Posts: 1,018
    Thanks for the post. I think I remember you from back in the day when I was posting here regularly.


    Yea I know shifting left multiplies by a power of 2 and right shifting divides by a power of 2. What I want to know is:

    Take 400/20

    The result is of course 20. But how would I do this operation without using div type instruction? In other words, how would I do it with shr?




    20*20 is easy to multiply using shl.

    All it is, is 20 * 20=(20<<4 + 20<<2)
Sign In or Register to comment.