I have this problem where I am asked to multiply BX by 42 without using any mul
or div
instructions, presumably by using shl
or shr
. It is also required to do it in 5 lines.
How do you do such a thing ?
I didn't try anything, but the above requirement was to multiply BX by 32 in 1 line, so I just used SHL BX, 5
.
An out of the box solution with 4 lines only would be
xor ax,ax
mov cx,42
a: add ax,bx
loop a
Otherwise, the common approaches include shift and add using the binary representation of the constant 42 = 0b101010, as well as the Booth's encoding (turning a sequence of ones e.g. 0b11110 to one shift and one subtraction 0b100000 * A - 0b10 * A).
Additionally one can factor out the constant 42 = 2*3*7
, which would lead to 7A*6, which could be done as (A<<3 - A)*6, however that too needs 6 instructions.
One could possibly exploit the AAD
instruction with undefined behaviour, which can be used to multiply an 8-bit value by another 8-bit value coded as the immediate.