views:

194

answers:

2

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?

+1  A: 

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)

Chad Okere
A: 

You could always used BigInteger, which works on arbitrary sized integers, but that would be a lot more expensive than promoting to long and cast back as int. Is your intention to improve performance (hence you want a "pure integer" solution to avoid the time for casts) or to improve how readable/understandable the code is (in which case BigInteger might be neater)?

Ash