2字节有符号整数比较汇编算法问题排查求助
2字节有符号整数小于比较功能的实现问题
初始实现版本
我正在实现2字节有符号整数的小于比较功能,多次重写算法后仍无法覆盖所有测试用例。以下是最新版本代码:
MATH_lt_int: ; a < b, a: MATH_INT_INPUT_1, b: MATH_INT_INPUT_2 jsr MATH_clear_int_output ; I use too many subroutines, sorry. lda MATH_INT_INPUT_1 + 1 eor MATH_INT_INPUT_2 + 1 bmi @different_sign ; eor our high bytes and check ; the neg flag to see if they differ lda MATH_INT_INPUT_1 + 1 ; if one is positive here, they both must be bpl @both_positive @both_negative: ; we have to do an inverted comparison here ; because if a < b then -b < -a sec lda MATH_INT_INPUT_1 + 1 ; check high byte first cmp MATH_INT_INPUT_2 + 1 bcc @not_less_than ; inverted because negative sec lda MATH_INT_INPUT_1 ; low byte next cmp MATH_INT_INPUT_2 ; the problem seems to be somewhere around here bcc @not_less_than ; inverted because negative beq @not_less_than jmp @less_than ; inverted because negative @both_positive: ; we get to do a straight-up comparison here sec lda MATH_INT_INPUT_1 + 1 ; check high byte first cmp MATH_INT_INPUT_2 + 1 bcc @less_than sec lda MATH_INT_INPUT_1 ; low byte next cmp MATH_INT_INPUT_2 bcc @less_than jmp @not_less_than @different_sign: ; if they have different signs, the negative one is smaller lda MATH_INT_INPUT_1 + 1 bmi @less_than ; are we the negative one? Than we're @less_than jmp @not_less_than @less_than: lda #1 jmp @return @not_less_than: lda #0 @return: sta MATH_INT_OUTPUT ; return rts
测试结果
50<50==0 => 0 50<60==1 => 1 60<50==0 => 0 -50<-60==0 => 1 -60<-50==1 => 1
当前问题:当a>b且两者均为负数时,应返回0,但实际返回1,问题疑似出在@both_negative段的第二条bcc @not_less_than语句附近。
更新后的简化版本
感谢@penguin359的建议,我将代码简化为如下版本,但仍无法正确处理负数比较:
MATH_lt_int: ; a < b, a: MATH_INT_INPUT_1, b: MATH_INT_INPUT_2 jsr MATH_clear_int_output ; I use too many subroutines, sorry. sec lda MATH_INT_INPUT_1 + 1 ; check high byte first cmp MATH_INT_INPUT_2 + 1 bmi @less_than sec lda MATH_INT_INPUT_1 ; low byte next cmp MATH_INT_INPUT_2 bmi @less_than jmp @not_less_than @less_than: lda #1 jmp @return @not_less_than: lda #0 @return: sta MATH_INT_OUTPUT ; return rts
测试结果
50<50==0 => 0 50<60==1 => 1 60<50==0 => 0 -50<-60==0 => 0 -60<-50==1 => 0
内容的提问来源于stack exchange,提问作者JShoe
相关产品推荐
相关产品推荐

