User Tools

Site Tools


This is an old revision of the document!

To add a signed 8-bit delta to a 16-bit value, we need to sign-extend the delta to a full 16 bits. The low byte can be added as normal, but the upper byte needs to be $00 or $ff based on the sign of the low byte.

Using only the accumulator:

 ; Standard low byte addition
 lda delta
 adc value
 sta value
 ; Sign extend the high byte
 lda delta
 and #$80    ; Extract the sign bit
 beq :+      ; If zero, add #$00 (+ carry)
  lda #$ff   ; Else, add $ff (+ carry)
:adc value+1
 sta value+1

The following version is 2 bytes shorter & 1 cycle faster, using .X:

 ; Precalculate the sign-extended high byte in .X
 ldx #$00
 lda delta
 bpl :+
  dex        ; decrement high byte to $ff for a negative delta
 ; Normal 16-bit addition
 adc value   ; .A still holds delta
 sta value
 txa         ; .X is the high byte
 adc value+1
 sta value+1

White Flame

base/signed_8bit_16bit_addition.1538100659.txt.gz · Last modified: 2018-09-28 04:10 by white_flame