Search code examples
assemblygccavrmodulointeger-division

mod (%) in AVR assembly - __divmodhi4


I'm trying to do %10 in AVR assembly.

I created a simple c file

int main()
{
  int k=19;
  int j;
  j = k%10;
  return 0;
}

which I then compiled into assembly, giving

    ldi r24,lo8(19)
    ldi r25,0
    std Y+2,r25
    std Y+1,r24
    ldd r24,Y+1
    ldd r25,Y+2
    ldi r18,lo8(10)
    ldi r19,0
    mov r22,r18
    mov r23,r19
    rcall __divmodhi4
    std Y+4,r25
    std Y+3,r24
    ldi r24,0
    ldi r25,0

How does __divmodhi4 work and where are the results stored?


Solution

  • Since AVR does not have hardware divider, the AVR-GCC compiler has to use complex functions to perform such operations.

    __divmodhi4 - one of those functions. It divides signed 16 bit integer, stored in r25:r24, by another signed 16 bit integer in r23:r22.

    Returns 16-bit quotient in r23:r22 and remainder in r25:r24

    You should see __divmodhi4 in the same disassembly where you see your own code.

    also you can see find sources of the GCC library for example, here