Random Integers (J2ME)

So, I'm studying J2ME, and for some reason (maybe the wrong version of CLDC?) I can't use random.getNext(n). I can't specify the range of the random number. What a pain.

I wanted to avoid doing floating point math, and fell back on a C trick. To get a random number from 0 to 500:

import java.util.Random;
Random r = new Random();
int myNum;
myNum = ((r.getNext() & 0xffff) * 500 ) >> 16;

r.getNext() returns a random int, which is 32 bits.

& 0xffff masks off the upper 16 bits, leaving 16 lower bits of randomness.

So our range of random numbers is 0 to 65535. We multiply this by our desired range.

>> 16 shifts the bits to the right. >> 16 is equivalent to dividing by 65535.

So, what this calculates is int((random_smallint / 65536) * range).

The trick is that we don't do any divisions, and we only multiply once, so it's probably faster.

Picture 005.jpg14.66 KB