在程序集中添加数组时找到数组的最低值
finding the lowest value of an array while adding them in assembly
我正在学习汇编,最近转向有符号数主题。在我坚持的一个练习中。有一个数组 array DB +53, -87, -45, +23, -79, +28, -90, +75, -39
,我想在添加它们时找到最低值。
例如:
让最低值 = 0
在前 2 次迭代中 --> 53+(-87) = -34 变得最低。 -34 +(-45) = -79 变低等。
我试图实现一个循环,但由于溢出,代码无法处理。
感谢任何帮助。
鉴于数组被定义为包含有符号字节,因此很容易使用字节大小的寄存器。这可能会迅速产生溢出。因此,最好使用字大小的寄存器。它所需要的只是使用 CBW
指令将字节值从 AL
符号扩展为 AX
。
mov si, 9 ; Number of elements
xor dx, dx ; Sum
mov cx, 32767 ; Current lowest
mov bx, offset array ; Address of array
again:
mov al, [bx] ; Fetch next byte element
cbw ; Sign-extend to word
add dx, ax ; Add to the sum
cmp dx, cx ; Is it less (signed comparison) ?
jnl NotLess
mov cx, dx ; Only replace if less than previous lowest
NotLess:
inc bx ; To next byte element
dec si
jnz Again
CX
寄存器 (-197) 具有 LowestValueWhileAdding。
DX
寄存器 (-161) 有 Sum.
我正在学习汇编,最近转向有符号数主题。在我坚持的一个练习中。有一个数组 array DB +53, -87, -45, +23, -79, +28, -90, +75, -39
,我想在添加它们时找到最低值。
例如:
让最低值 = 0
在前 2 次迭代中 --> 53+(-87) = -34 变得最低。 -34 +(-45) = -79 变低等。 我试图实现一个循环,但由于溢出,代码无法处理。 感谢任何帮助。
鉴于数组被定义为包含有符号字节,因此很容易使用字节大小的寄存器。这可能会迅速产生溢出。因此,最好使用字大小的寄存器。它所需要的只是使用 CBW
指令将字节值从 AL
符号扩展为 AX
。
mov si, 9 ; Number of elements
xor dx, dx ; Sum
mov cx, 32767 ; Current lowest
mov bx, offset array ; Address of array
again:
mov al, [bx] ; Fetch next byte element
cbw ; Sign-extend to word
add dx, ax ; Add to the sum
cmp dx, cx ; Is it less (signed comparison) ?
jnl NotLess
mov cx, dx ; Only replace if less than previous lowest
NotLess:
inc bx ; To next byte element
dec si
jnz Again
CX
寄存器 (-197) 具有 LowestValueWhileAdding。
DX
寄存器 (-161) 有 Sum.