2

I came across the following piece of 16-bit x86 code for multiplying a value by 40, using just shifts and additions:

; BX holds the value we want to multiply.
; The result is stored in AX.
MOV AX, BX

; Multiply by 4 using two shifts
SHL AX, 1
SHL AX, 1

; Add the original value, this gives us BX * 5
ADD AX, BX

; Now multiply by 8 using three shifts for the final result
SHL AX, 1
SHL AX, 1
SHL AX, 1

Now what I'd like to know is why this code uses multiple shifts in a row instead of just doing SHL 2 and SHL 3. It was almost certainly written by hand, so I assume there was some speed benefit or something. Does anyone have any insights?

The code was written in 1991 and was targeting 286 and 386 class machines.

2 Answers 2

2

Shift/rotate with an immediate byte didn't exist until the 80186. On the 8086 only shifting/rotating by 1 or CL was possible. So it is likely you have some 8086 code.

1
  • Ahh I see, yeah that would make a lot of sense! Commented Nov 9, 2022 at 22:33
0

There are two reasons I can think of and that has to do with overflow. Perhaps SHL AX, 1 and SHL AX 3 deal with overflow differently? otherwise, I don't see a difference unless there is possible some speed difference.

1
  • Ah, that's an interesting point! I don't believe it applies in this case, but thanks for sharing! Commented Nov 10, 2022 at 14:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.