2

There is a way to compute the mod operation, without using DIV or IDIV in assembly x86 language?

For instance, one could use DIV in order to take the remainder of the division. But, instead to use DIV, there are other options?

Giuseppe Canto
  • 159
  • 1
  • 1
  • 14
  • Yes, but which are good depend on the situation. Is there more context to this question or is it more theoretical? – harold Nov 27 '16 at 20:05
  • Yes, is for an exercise @harold . 8-bits value divided by 8-bits value. – Giuseppe Canto Nov 27 '16 at 20:19
  • I wonder why you don't see basic-math naive inefficient way (you would mention it in question, right?): `while (divisor <= number) number -= divisor;` will reduce `number` to `0` - `divisor-1` range, which means it will be "remainder" (needs of course initial validation of values for corner cases). Which should be easy to code in ASM. – Ped7g Nov 28 '16 at 09:25

1 Answers1

5
  • You can always write the division algorithm yourself, completly not using the DIV or IDIV instructions.

  • There's of course a range of modulo's where you basically just need an AND instruction:

    and eax, 255    ;Gives modulo 256
    and eax, 15     ;Gives modulo 16 
    
Sep Roland
  • 33,889
  • 7
  • 43
  • 76
  • Thank you. This is exactly what I was searching for! Maybe, the use of the bit-wise AND works better in terms of performances. Is it right? – Giuseppe Canto Nov 27 '16 at 20:41
  • There's not much that can beat a single `and` instruction in terms of performance. – Sep Roland Nov 27 '16 at 20:53
  • 1
    @GiuseppeCanto: See http://stackoverflow.com/questions/40354978/why-is-this-c-code-faster-than-my-hand-written-assembly-for-testing-the-collat/40355466#40355466 to learn how much slower DIV is than SHR or AND when the divisor or modulus is a power of 2. It's at least 20 to 30 times faster. – Peter Cordes Nov 28 '16 at 04:48