x86程序集-整数舍入问题



我正试图用汇编语言四舍五入到最接近的整数,我一直在努力找出它。例如,如果我执行除法函数137/6,我如何将结果四舍五入到最接近的整数?

对于正值,在除法之前,将分母的一半加到分子上。我把更复杂的负价值观的情况留给你。

mov ecx, [denominator]      ; divisor
mov eax, ecx                ; copy to numerator register
shr eax, 1                  ; half divisor
add eax, [numerator]        ; add to numerator
div ecx                     ; (numerator + denominator/2) / denominator

对于正数,"向正无穷大取整一半"(注释中的解释):

xor edx, edx                ; Clear EDX for division
mov eax, [numerator]        ; Dividend stored in the data section (eg. dd 137)
mov ecx, [denominator]      ; Divisor stored in the data section (eg. dd 6)
div ecx                     ; EDX:EAX / ECX = EAX remainder EDX
shl edx, 1                  ; EDX *= 2
cmp edx, ecx                ; Fraction part < 0.5 (remainder*2 < divisor) ?
jb .done                    ; Yes: skip rounding
add eax, 1                  ; No: round half up (http://en.wikipedia.org/wiki/Rounding#Round_half_up)
.done:                      ; EAX = rounded result of division

最新更新