mod & div...

Curious question - how does the VM actually do an integer mod operation?
There does not appear to be an ‘imod’ bytecode, and the ‘idiv’ doesn’t return the modulus (although I don’t know of any processor that doesnt return the mod when it does an integer divide).

I just so happen to want to do a divide and a mod at the same time, and I don’t particularly wish to do:


int div = a / b;
int mod = a - (div*b);

Any suggestions?

  • Dom

PS: This is in a loop I am looking at running >5000 times a frame, so I would really like to do it quite quickly :slight_smile:

Well, the first question is: what happens if you do


c1 = a % b;
c2 = a / b;

PS what are you doing 5k divs and mods for in one frame? Is there possibly a better algo?

In particular, there are some interesting identities when you start working in modulus arithmetic (which are heavily used in crypto), and there’s a small chance some of those could help you rearrange your algo…

[quote]Curious question - how does the VM actually do an integer mod operation?
There does not appear to be an ‘imod’ bytecode,
[/quote]
Remainder: irem, lrem, frem, drem.

Ah - rem for remainder!
There I was looking for the conventional one used by most of the known computing world!

Still - does it reuse the result from a divide once the bytecode is compiled?

As to what I am doing - its a good old fashioned software renderer to get 3D running for Java 1.1. The mod/div is for generating DDA values for the edge gradients - although I may not be doing that now :slight_smile:

  • Dom

It’s up to the JVM to make the div followed by mod optimization. I doubt they make this optimization because it occurs very seldom.

Here is a code example and the generated byte code:


class Test {
  public void test(int a, int b) {
    int y = a / b;
    int x = a % b;
  }
}

javap -c Test
...

Method void test(int, int)
   0 iload_1
   1 iload_2
   2 idiv
   3 istore_3
   4 iload_1
   5 iload_2
   6 irem
   7 istore 4
   9 return