is this the right way to use cbw in Mul?

放肆的年华 提交于 2021-02-10 11:58:14

问题


I get the Multiplication from 8bit and 8bit register. But, when you have one in 16 bit, and one in 8bit, how do we do the conversion before multiplying:

Question : need to provide code fragments for 260*19, and print the results. I did:

mov Ax,260
mov Al,19
cbw;
Mul Ax 
PutInt Ax

回答1:


mov Ax,260
mov Al,19

The AL register is the lowest half of the AX register.

            AX
    /-----------------\
MSB xxxx xxxx xxxx xxxx LSB
    \-------/ \-------/
        AH        AL

The 2nd instruction mov al, 19 thus erroneously overwrites your 1st number.

Mul Ax 

The byte-sized mul instruction multiplies the ALregister by the specified byte-sized operand.
The word-sized mul instruction multiplies the AXregister by the specified word-sized operand.

Using mul ax then would calculate AX * AX, which is not what you wanted. You want to multiply different numbers.

Using AX together with another register like BX solves both problems.


What to do with that cbw depends on how we look at the code.

  • If you work with the numbers as immediates (260, 19), then just use a word-sized register even for the small number 19:

    mov     bx, 260
    mov     ax, 19
    mul     bx       ; Product AX * BX is in DX:AX but here DX=0
    PutInt  ax
    

    or even let the assembler do the multiplication:

    mov     ax, 260 * 19
    PutInt  ax
    
  • If the numbers come from memory (different sized variables) then you need to extend the smaller one.

    • Unsigned numbers, use mulfor unsigned multiply

      mov     bx, wNum  ; [0,65535]
      mov     al, bNum  ; [0,255]
      mov     ah, 0
      mul     bx        ; Product AX * BX is in DX:AX
      PutInt  ax
      

      I advice against using cbw in this case! Using cbw would criple all numbers from 128 upwards.

    • Signed numbers, use imulfor signed multiply

      mov     bx, wNum  ; [-32768,32767]
      mov     al, bNum  ; [-128,127]
      cbw
      imul    bx        ; Product AX * BX is in DX:AX
      PutInt  ax
      

      cbw is the right choice to extend the signed byte from AL.



来源:https://stackoverflow.com/questions/55645909/is-this-the-right-way-to-use-cbw-in-mul

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!