0

I have been trying to divide two 32-bit registers by 10. I know how to divide a register if a dividend is 32-bit like the following code, but I cannot solve if it's 64-bit.

div     s8, s0, a6 # divide a result by 10 (for example, 1234->123)
mul     s6, s8, a6 # multiply s8 by 10 (for example, 123->1230)
sub     s7, s0, s6 # the result - s6 (for example, 1234-1230->4)
beqz    s7, output # if s7 is zero, jump

And I found a tips that

The division is more tricky. You may either implement regular binary division by comapare, shift and subtract or use another method: Think of a 64bit number ab (where a and be are 32-bit numbers) as of a * 2^32 + b. Express 2 ^32 as x * 10 + y. Then ab / 10 = x + (y *a + b) / 10. If you apply this method twice, you may reduce 64-bit division by 10 to a 32-bit one.

But I cannot understand why I can get a 32-bit number if I apply this method twice.

Yuka
  • 11
  • 3
  • Does this answer your question? [64 bit by 32 bit division](https://stackoverflow.com/questions/3472117/64-bit-by-32-bit-division) – Raymond Chen May 29 '22 at 22:40
  • https://godbolt.org/z/1YafT43js - GCC/clang use a helper function, `__udivdi3`. https://github.com/glitchub/arith64/blob/master/arith64.c shows portable C implementations, https://github.com/gcc-mirror/gcc/blob/05f220c205b7e4182b17d8747c80a288af515d4e/libgcc/config/riscv/div.S#L73 shows libgcc hand-written asm source. But it's doing 32-bit / 32-bit division with bit-shifts if used on RV32 instead of RV64. There must be a 2-register version somewhere, but it wouldn't be optimized for 64/32 except maybe for checking for that special case. – Peter Cordes May 30 '22 at 01:12
  • Obviously the easiest way this would be easier on an RV64, since I don't think RISC-V has narrowing division (with a 64-bit dividend and 32-bit divisor / quotient / remainder). If you did, it would only take one div/rem for the high half and then a divide of the low part using the remainder as the high half of the dividend. – Peter Cordes May 30 '22 at 02:41
  • 1
    I don't think the 64-bit architecture tag is appropriate here, because you're trying to divide a ***64-bit value*** on a ***32-bit architecture***. If you were using a 64-bit RISC V architecture, dividing a 64-bit value would be trivial. – Erik Eidt May 31 '22 at 15:51

0 Answers0