E
E
etc2010-10-12 18:26:54
Atmel AVR
etc, 2010-10-12 18:26:54

AVR Assembler: decomposing a number into digits

Hello! There is an ATMega128 and an 8-bit register r16, which contains a number from 0 to 255. You need to get registers r17, r18, r19, which will contain the digits of the number from r16. What is the best way to do it, in which direction to dig? I guess you need to use division with a remainder. First, divide r16 by 100, write the first digit, then divide the remainder by 10 - write the second digit, and finally write the final remainder to the third digit. But here another question already arises - how to divide with the remainder? Thanks in advance.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
apangin, 2010-10-12
@etc

I have never programmed on the AVR, so I will limit myself to the algorithm.
1 way, short.

    while (r16 >= 100) { r17++; r16 -= 100; }
    while (r16 >= 10) { r18++; r16 -= 10; }
    r19 = r16;

2 way, fast.
    if (r16 >= 200) {
      r17 = 2;
      r16 -= 200;
    } else if (r16 >= 100) {
      r17 = 1;
      r16 -= 100;
    }
    if (r16 >= 50) { r18 = 5; r16 -= 50; }
    if (r16 >= 20) { r18 += 2; r16 -= 20; }
    if (r16 >= 20) { r18 += 2; r16 -= 20; }
    if (r16 >= 10) { r18++; r16 -= 10; }
    r19 = r16;

3 way if the chip supports the MUL instruction.
Take advantage of the fact that (N / 10) = Hi(N * 0xCD) >> 3;

E
ertaquo, 2010-10-12
@ertaquo

Sorry, I didn’t work with this assembler ... But as I understand it, if there is a division without a remainder, then the remainder of the division can be obtained like this: num - (num div 10) * 10

S
Sannis, 2010-10-12
@Sannis

If your number is limited to 255, then you can use conditions and bit shifts. A little long, but sure. And faster than dividing by 10 (100).

E
etc, 2010-10-13
@etc

Thanks to apangin for the interesting algorithm.
Today I asked this question to the teacher. I received a similar algorithm in response:
while (r16 > 0) {
if (r19 == 9) {
r18++;
r19 = 0;
}
if (r18 == 9) {
r17++;
r18 = 0;
}
r19++;
r16--;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question