23

How do you add a 16 and a 8 bit register with carry (for example, HL, and A)?

Martin
  • 37,119
  • 15
  • 73
  • 82
xkdkxdxc
  • 511
  • 5
  • 9
  • OMG. I haven't done any Z80 programming since POKE-ing machine code into a Sinclair ZX-80 REM statement in 1980 or so. My loss, it's an excellent processor for some tasks right through to today. Dunno, maybe this will help: http://nemesis.lonestar.org/computers/tandy/software/apps/m4/qd/opcodes.html – T.J. Crowder Feb 11 '10 at 21:43
  • 7
    +1 just for being a z80 question. Good times. – Kevin Montrose Feb 11 '10 at 21:46
  • Heh... haven't touched it since the Spectrum either (much preferred it to the register-starved 6502). Carl's edited answer looks right from what I remember, though I can't vote it up now, having already vote-changed over the BC order issue. Ah well. – bobince Feb 11 '10 at 21:53
  • 1
    ZX-80? You sissies! I had a TRS-80 Model I Level II with full blown 16KB of mem! :-) – Serge Wautier Jan 13 '12 at 10:12

3 Answers3

28

I would like to point out that the checked response (by Carl Norum) is correct, but not the best answer. The following shows the speed of the two strategies with clock cycles. Using the right solution saves time, and won't destroy a second 16 bit register pair.

  4   ld c,a            4   add a,l
  7   ld b,0            4   ld l,a
  11  add hl,bc         4   adc a,h
                        4   sub l
                        4   ld h,a

However, the solution on the right does take an extra byte of code.

James
  • 425
  • 4
  • 6
  • 5
    I don't agree with the statement "fastest=best". Memory is usually an expensive resource on such machines. Hence "uses one more byte" is an important downside. OTOH, the "saves one register" argument is a nice one. Up to the OP to make his pick – Serge Wautier Jan 19 '12 at 17:03
  • 2
    Good point. I should have said "is not *necessarily* the best answer". – James Feb 26 '14 at 06:49
  • 2
    Registers can be a *very* precious resource though, so not using another 2 extra registers is a big win too. – Pepijn Aug 07 '16 at 13:38
14

You can't do it directly. You need to copy A into a 16-bit register pair and then do the add:

LD  B, 0
LD  C, A
ADC HL, BC
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
-4

From http://nemesis.lonestar.org/computers/tandy/software/apps/m4/qd/opcodes.html

Add Byte with Carry-In Instructions
8080 Mnemonic Z80 Mnemonic  Machine Code Operation
ADC  M        ADC A,(HL)    8E           A <- A + (HL) + Carry
Roland Bouman
  • 31,125
  • 6
  • 66
  • 67
  • This is adding the contents of an 8 bit memory location to the 8 bit accumulator A. – Paul R Feb 11 '10 at 21:48
  • `(HL)` means the *contents* of the byte address pointed to by HL, though... I don't *think* that's what the OP is trying to do. – bobince Feb 11 '10 at 21:49