BTST无法按预期工作以确定数字是否为奇数

时间:2018-11-08 08:43:18

标签: 68000

我对为什么此代码无法按预期工作感到困惑。据我了解,BTST.L #1,D1检查D1中存储的值的最后一位是否为1,在这种情况下D1中的值将为奇数,并且程序将分支到ADDSUM。

它似乎可以正确地使用某些值(9 * 2、8 * 2或10 * 10),但是当我尝试执行其他操作时会失败(11 * 11给我110,与10 * 11相同)。我相信每当乘数为奇数时。

START:
              MOVE.W #MULTIPLICAND,D0  ; Set D0 equal to the multiplicand
              MOVE.W #MULTIPLIER,D1    ; Set D1 equal to the multiplier
              MOVE.L #00000000,D2      ; Clear D2 as it will be used to store the product

LOOP          BTST.L #1,D1     ; Check if D1 is odd
              BEQ ADDSUM      ; If so branch to ADDSUM

RETURN        CMP #$01,D1      ; Check if the multiplier is equal to 1
              BEQ END         ; If so, terminate the loop

              ASL #1,D0       ; Multiply the multiplicand by 2
              ASR #1,D1       ; Divide the multiplier by two

              BRA LOOP        ; Branch back to the top of the loop

ADDSUM        ADD.W D0,D2     ; Add D0 to D2
              BRA RETURN      ; After adding, we have to branch back to where we were in the loop

END           SIMHALT

1 个答案:

答案 0 :(得分:1)

我知道了。我想我会把它发布为答案,以防万一有人偶然发现这个问题。

事实证明,我不理解BTST.L #1,D1指令的工作方式。我认为原始示例中的代码应该检查D1中的最后一位是否等于1。实际上,BTST通过将Z条件代码标志设置为1来工作。测试为0。指令中的#1指定它正在测试从右数第二位。

为了确定偶数/奇数,最右边的位是必须测试的位。我通过将代码更改为以下内容来修复了代码:

LOOP          BTST.L #0,D1    ; Check if D1 is even (Z-flag will be set to 1 if bit is zero)
              BNE ADDSUM      ; BNE will branch to ADDSUM if Z-flag is not set (meaning D1 is odd)

希望这可以帮助遇到相同问题的其他人。

相关问题