Can you randomly bitwise shift an integer left or right?

I encountered an IllegalArgumentException for Random class when I’m randomizing my bitwise shift factor in one direction.


this.pixels[tgt + xx] = biomeColor - (biomeColor >> r.nextInt(4));

I thought this is allowed. Or I’m not doing it right?

Are you really sure, that you called the method with [icode]4[/icode]?

This is what the docs say:
http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt(int)

The doc says, the implementation looks like this:


 public int nextInt(int n) {
   if (n <= 0)
     throw new IllegalArgumentException("n must be positive");

   if ((n & -n) == n)  // i.e., n is a power of 2
     return (int)((n * (long)next(31)) >> 31);

   int bits, val;
   do {
       bits = next(31);
       val = bits % n;
   } while (bits - val + (n-1) < 0);
   return val;
 }

Therefore the only reason you might get an [icode]IllegalArgumentException[/icode] is when you provide a value lower [icode]<= 0[/icode].

nextInt() will occasionally give you a zero… which is not a legal argument to << or >>. A bit arbitrary but there you go.

Cas :slight_smile:

Ah!! That’s the problem. So trivial… Much appreciated. :stuck_out_tongue:

Wut. I didn’t know that and it doesn’t seem logical to me, but well :smiley:
That’s like throwing an IllegalArgumentException when you do [icode]5 + 0[/icode] or [icode]42 * 1[/icode]

Now I look at it, it does seem strange…
* princec checks…

Cas :slight_smile:

It is indeed wrong, 1 << 0 is legal. So I surmise that the code posted above is not actually the code that is throwing the exception.

Cas :slight_smile:

… which brings me to a request for tom_mai… When you get an exception and want to know what it’s caused by, please post the full stack trace.

https://lh4.googleusercontent.com/-Y04AM5bwZHA/TwnsH3DDQjI/AAAAAAAAAiA/tJWgEoPX0sU/w506-h720/DuJYY.jpg

Cas :slight_smile:

But… But…

Problem’s solved… :’(

Just to chime in…

If [icode] biomecolor [/icode] ever did equal to 0 it would break the code as 0 - 1 due to the shift is in fact -1.

Yep, hence I hardwired the [icode]biomeColor[/icode] to color-specific constants.

Shifts are defined for all inputs

Glad to know. :smiley:

Just not what you might expect* ;D
*right-hand operand is truncated to 5 bits(for an int shift) or 6 bits (for a long shift).

I came a cropper of this behaviour some time ago.