javaunsigneddivision

Java unsigned division without casting to long?


I have written an interpreter that requires me to perform 32-bit division of unsigned integers. In Java, I can do this as:

reg[a] = (int) ((reg[b] & 0xFFFFFFFFL) / (reg[c] & 0xFFFFFFFFL));

But I would like to avoid the conversion to long and back to int. Java already gives the unsigned right shift operator >>> for that special case, so maybe there is a clever way to do unsigned division in the same way.

Note that add and multiply work fine, since two's compliment numbers just work.

Is there a better way in Java to do this?


Solution

  • Well, if you shift down by one bit, you could divide the resulting two numbers, then shift up twice (because the resulting number would be 4 times smaller). But that would only work on even numbers, since you would lose the least significant bit.

    I don't really think it would save you any time to check for that condition. (or check for numbers smaller then 231)