Software - Median of 3 bytes
Here is a short and fast routine to find the median (i.e. the middle value) of three bytes A, B, and C (A and B must be in consecutive memory locations):
; A, X, and Y registers assumed to be in 8-bit width mode
; for 65802 or 65816 microprocessors.
AB DS 2
C DS 1
LDX #1
LDA AB
CMP AB+1
BCC .1
LDA AB+1
DEX
.1 CMP C
BCS .2
LDA AB,X
CMP C
BCC .2
LDA C
.2 RTS
In this version, enter with the three bytes in the A, X, and Y registers; the median is returned in the accumulator.
STX .M
CMP .M
BCS .1 ; branch if a >= m
STA .M ; a is < x, so a -> m x -> a
TXA
.1 CPY .M ; a is now >= m
BCC .2 ; if y < m then m is the median
STY .M ; y >= m, so m is smallest, so y -> m
CMP .M ; the smaller of m and a is the median
BCC .3 ; branch if a is smaller
.2 LDA .M
.3 RTS
.M DS 1 ; temporary storage
page revision: 1, last edited: 24 Jun 2010 06:32