Efficiently handling signed overflow in PASM?
I'm trying to calculate C = (A+B)/2 and C = (A-B)/2 in PASM, where A, B and C are 32 bit signed integers.· I'd like to gracefully and efficiently handle overflow of the intermediate result.· For unsigned addition I'd code it as:
But handling signed values and subtraction is making my head hurt.
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Composite NTSC sprite driver: Forum
NTSC & PAL driver templates: ObEx Forum
OnePinTVText driver: ObEx Forum
mov c, a add c, b wc rcr c, #1
But handling signed values and subtraction is making my head hurt.
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Composite NTSC sprite driver: Forum
NTSC & PAL driver templates: ObEx Forum
OnePinTVText driver: ObEx Forum

Comments
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Visit some of my articles at Propeller Wiki:
MATH on the propeller propeller.wikispaces.com/MATH
pPropQL: propeller.wikispaces.com/pPropQL
pPropQL020: propeller.wikispaces.com/pPropQL020
OMU for the pPropQL/020 propeller.wikispaces.com/OMU
mov c, a
sar c, #1
mov variable, b
sar variable, #1
subs c, variable
overflow is avoided instead of handled.
Post Edited (Alsowolfman) : 11/11/2009 9:15:07 PM GMT
[b]mov[/b] c,a [b]adds[/b] c,b [b]wc[/b] [b]if_nc[/b] [b]sar[/b] c,#1sum [b]mov [/b] c,b ' 7fff ffff 0001 8001 [b]adds [/b] c,a [b]wc[/b] '+7fff +ffff +0001 +8001 [b] [/b] '=fffe c =ffff nc =0002 nc =0002 c [b]sar [/b] c,#1 '=ffff =ffff =0001 =0001 [b]if_c[/b] [b]xor[/b] c,_0x8000_0000 '=7fff =ffff =0001 =8001 dif [b]neg [/b] c,b [b]adds [/b] c,a [b]wc[/b] [b]sar [/b] c,#1 [b]if_c[/b] [b]xor[/b] c,_0x8000_0000 _0x8000_0000 [b]long[/b] $8000_0000It's easiest, thanks to the neg instruction, to treat both as sums. In this case overflow occurs iff two positive numbers sum to a negative or two negative numbers sum to a positive.
-Phil
Post Edited (Phil Pilgrim (PhiPi)) : 11/11/2009 10:17:33 PM GMT
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Composite NTSC sprite driver: Forum
NTSC & PAL driver templates: ObEx Forum
OnePinTVText driver: ObEx Forum