Java unsigned splitting without casting in length?

I wrote an interpreter that requires me to perform 32-bit division of unsigned integers. In Java, I can do it like:

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

But I would like to avoid converting to long and back to int. Java already provides an unsigned right shift operator >>> for this special case, so there may be a smart way to do unsigned division in the same way.

Please note that adding and multiplying work fine, as only two compliment numbers work.

Is there a better way in Java to do this?

+4
source share
2 answers

Well, if you shift by one bit, you can divide the resulting two numbers, and then shift two times (because the resulting number will be 4 times smaller). But this will only work on even numbers, since you will lose the least significant bit.

I really do not think it will save you at any time to check this condition. (or check that the numbers are less than 2 31 )

+1
source

You can always use BigInteger , which works with integers of arbitrary size, but it will be much more expensive than moving to long and discarded as int . Is your intention to improve performance (therefore, you want a β€œclean whole” solution to avoid time for throws) or to improve understanding and understanding of the code (in this case, BigInteger may be more accurate)?

-one
source

All Articles