Port of Random generator from C to Java?

Most of the time there is no need to use larger numeric types for simulating unsigned types in Java.

For addition, subtraction, multiplication, shift left, the logical operations, equality
and casting to a smaller numeric type
it doesn’t matter whether the operands are signed or unsigned,
the result will be the same regardless, viewed as a bit pattern.

For shifting to the right use >> for signed, >>> for unsigned.

For signed casting to a larger type just do it.

For unsigned casting from a smaller type to a long use & with a mask of type long for the smaller type.
E.g., short to long: s & 0xffffL.

For unsigned casting from a smaller type to an int use & with a mask of type int.
E.g., byte to int: b & 0xff.

Otherwise do like in the int case and apply a cast on top.
E.g., byte to short: (short) (b & 0xff).

For the comparison operators < etc. and division the easiest is to cast to a larger type and do the operation there.
But there also exist other options, e.g. do comparisons after adding an appropriate offset.

Leave a Comment