6502 16-bit unsigned += 8-bit signed

Are you new to 6502, NES, or even programming in general? Post any of your questions here. Remember - the only dumb question is the question that remains unasked.

Moderator: Moderators

Post Reply
User avatar
Ben Boldt
Posts: 549
Joined: Tue Mar 22, 2016 8:27 pm
Location: Minnesota, USA

6502 16-bit unsigned += 8-bit signed

Post by Ben Boldt » Mon May 11, 2020 6:58 pm

I am looking for a good way to take a 16-bit unsigned value in RAM, and update it by adding a signed 8-bit value to it. Adding values $00-7F should make the 16-bit value larger and adding values $80-FF should make the 16-bit value smaller. 16-bit rolling over 0000->ffff, ffff->0000 from this operation is 'don't care'.

I think something like this could work (haven't tried it though)

Code: Select all

    lda 8bit ; load signed 8-bit value into A
    bmi subtract
add
    clc ; clear carry bit
    adc 16-bitLSB ; add 8-bit to the LSB, which may set the carry bit
    sta 16-bitLSB ; store updated LSB back to memory
    lda 16-bitMSB ; load MSB into A
    adc #$00 ; add the carry bit to the MSB
    sta 16-bitMSB ; store updated MSB back to memory
    jmp done
subtract
    clc ; clear carry bit
    adc 16-bitLSB ; add the negative 8-bit value to the LSB, which may set the carry bit
    sta 16-bitLSB ; store updated LSB back to memory
    lda 16-bitMSB ; load MSB into A
    sbc #$00 ; subtract the inverse of the carry bit from the MSB
    sta 16-bitMSB ; store updated MSB back to memory
done
Is this pretty typical or is there a better way?

lidnariq
Posts: 9383
Joined: Sun Apr 13, 2008 11:12 am
Location: Seattle

Re: 6502 16-bit unsigned += 8-bit signed

Post by lidnariq » Mon May 11, 2020 7:03 pm

Add the LSBytes, sign-extend the 8-bit number, and then add this extension to the MSbyte.

tepples
Posts: 21973
Joined: Sun Sep 19, 2004 11:12 pm
Location: NE Indiana, USA (NTSC)
Contact:

Re: 6502 16-bit unsigned += 8-bit signed

Post by tepples » Mon May 11, 2020 7:24 pm

Here's an obvious way:

Code: Select all

clc
lda amount_to_add
bpl @no_neg  ; If amount is $80-$FF, subtract $100
  dec accum_hi
@no_neg:
adc accum_lo
sta accum_lo
lda #0
adc accum_hi
sta accum_hi

User avatar
Ben Boldt
Posts: 549
Joined: Tue Mar 22, 2016 8:27 pm
Location: Minnesota, USA

Re: 6502 16-bit unsigned += 8-bit signed

Post by Ben Boldt » Mon May 11, 2020 8:29 pm

Oh wow, your link has a perfect example what I am trying to do:
If you're just trying to add an 8-bit delta to a 16-bit value, you could try subtracting 256 from the value by decrementing the high byte if the value is negative and then adding as if it were unsigned.

Code: Select all

  lda delta_value
  bpl notneg
  dec value_hi
notneg:
  clc
  adc value_lo
  sta value_lo
  lda #0
  adc value_hi
  sta value_hi
I knew there must be a simpler way. Thanks!


Edit:

oops sorry I missed your post tepples. thanks for your help.

Post Reply