Assembly - Multiplication by a constant

February 2017

You can make a multiplication using multimedia instructions like imul and mul in the assembly language code, as Mul name_register. The processor internally multiplies the programming codes by segregating the parameters of sizes, like for eax, ax and al, and then stores the result in eax or ax as "low" and results in edx or dx as "most significant", with the result last recorded being set, if the multiple is greater than a byte.

As multimedia files are huge in memory, you may need to shift values in eax to be multiplied on the register, and the register result must be eax, with the previous value overwritten. Nevertheless, if you need to multiply a register by a constant, put result in the register and then use a shortcut with the instruction "lea".


Short intro


Assembly languages are low-level languages for programming computers and were first developed in the 1950s. They are mostly known as second generation programming languages. An important feature of Assembly language, is that they eliminated much of the error-prone and time-consuming operations required in first-generation programming.

Multiplication in assembly


In assembly you can multiply two numbers using the instructions mul (unsigned numbers) and Imul. They are used as follows:

mul name_registry


The processor increases the content of eax or ax or al (depending on the size of the registry, which is given in the parameters) and then stores the result in eax, ax, edx or dx.

Using mul is quite troublesome because you will have to move the multiplied value to eax, the value to multiply to a different registry and the registry holding the result must be eax.

However, if you just want to multiply a registry by a constant and put the result in the registry of your choice, you can use a shortcut with the instruction "lea" (load effective address). This instruction is used to retrieve the address of a data in memory.

lea destination_registry, [memory_address]; place memory_address in destination_registry


The big advantage of this is that, by using a constant, you do not need to use up an extra memory address. Imagine that you want to multiply ecx by 7 and save the result in ebx, the command would be:
lea ebx, [ecx * 7]



Note: You can not multiply two registries together using this shortcut.

Related


Published by jak58. Latest update on February 20, 2012 at 05:59 AM by Virginia Parsons.
This document, titled "Assembly - Multiplication by a constant," is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (ccm.net).