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
.
CodePudding user response:
Factor 42 (decimal) equals 00101010 (binary), and orders of 1s in this notation are
1, 3, 5, hence the result will be
21 * N 23 * N 25 * N = 42 * N.
The code assumes CPU Intel 186 or better and the factor N loaded in BX
; product is returned in BX
, too.
Unfortunately, it needs six instructions, I didn't manage to spare a line.
SHL BX,1 ; BX=2*N
MOV AX,BX ; AX=2*N
SHL BX,2 ; BX=8*N
ADD AX,BX ; AX=2*N 8*N
SHL BX,2 ; BX=32*N
ADD BX,AX ; BX=2*N 8*N 32*N = 42*N
CodePudding user response:
A trio of solutions that have 6 lines and can run on emu8086 because that emulator does allow shifting by an immediate count, contrary to what a real 8086 CPU would allow!
On input BX = N
shl bx, 1 ; BX = N * 2
mov ax, bx ; AX = N * 2
shl bx, 2 ; BX = N * 8
add bx, ax ; BX = N * 10
shl bx, 2 ; BX = N * 40
add bx, ax ; BX = N * 42
mov ax, bx ; AX = N
shl bx, 2 ; BX = N * 4
add ax, bx ; AX = N * 5
shl bx, 2 ; BX = N * 16
add bx, ax ; BX = N * 21
shl bx, 1 ; BX = N * 42
but the above requirement was to multiply BX by 32 in 1 line
mov ax, bx ; AX = N
shl bx, 5 ; BX = N * 32
shl ax, 1 ; AX = N * 2
add bx, ax ; BX = N * 34
shl ax, 2 ; AX = N * 8
add bx, ax ; BX = N * 42