Z80 Routines:Math:Signed Math
From WikiTI
Here come useful routines that handle signed math.
Change Sign
;---> negate a negA: neg ;or: cpl / inc a
;absolute value of A AbsA: bit 7,a ret z neg ret
;Input: e - 8-bit signed number ;Output: a - 8-bit signed number ;Sample: abs(-2) = 2; abs(2) = 2 AbsAp: ld a,e rlca sbc a,a ;($FF if signed, $00 if not) ld b,a xor e sub b ;OR xor a sub e jp p,$+4 ld a,e
;---> negate hl ;input: hl ;ouput: hl negated ;destroys a negHL: xor a sub l ld l,a sbc a,a sub h ld h,a ret
Extend Sign
;a to bc (extend sign) ;inputs: a - 8-bit signed number ;outputs: bc - same 16-bit signed number AtoBCextendendsign: ld c,a rlca ; or rla sbc a,a ld b,a ret
; sign-extends e into de EtoDEextendsign: ld a, e rlca ; move sign bit into carry flag sbc a, a ; a is now 0 or 11111111, depending on the carry ld d, a ret
; sign-extends de into hlde DEtoHLDEextendsign: ld h, d add hl, hl ; move sign bit into carry flag sbc hl, hl ; hl is now 0 or 11111111 11111111, depending ret