0

My problem is that I don't know how to handle the addition when it gets out of the 8-Bit range.

My program runs with small Hex numbers like #02h + #05h but not with higher numbers like #0A9H + #0B5H.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847

1 Answers1

0

For 2 numbers, there's an asm trick: the carry flag holds the 9th bit of the ADD result, and we can right shift that 9-bit value with rotate-right through carry. 8051's RRC instruction does that.

   ADD A, R0
   RRC

Without that, see questions like How can I safely average two unsigned ints in C++? and Explanation of the safe average of two numbers

For more than 2 numbers, do extended-precision (using add-with-carry) to keep a wider sum.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
  • @Doomedtostudy: Not like this; you'd need a 12-bit sum to hold the largest possible result (`10 * 0xff` = 0x9f6). You might use RRC as part of extended-precision division when you're done, though. Since your divisor isn't even a power of 2 anymore, that part isn't just an extended-precision shift. If you need more help with that, ask a new question where you describe what you're actually trying to do (I didn't find this answer in an existing question, so this Q&A is hopefully useful to future readers in current form). Or just use `uint16_t` in C and see what an optimizing 8051 compiler does – Peter Cordes Mar 10 '21 at 07:29
  • Well thank you mate. I will ask another question than. – Doomedtostudy Mar 10 '21 at 07:40