javacard - Generate random number bounded between two numbers in Java Card -
how generate random number bounded between 2 number in java card? example number should generated between 0 , 50.
being intrigued question decided again make code contributions through stackoverflow. note have tested distribution of random numbers using securerandom
within java se. i'm reasonably sure code correct though.
so without further ado, code.
package nl.owlstead.jcsecurerandom; import javacard.framework.jcsystem; import javacard.framework.util; import javacard.security.randomdata; /** * generates numbers within range. class uses modulo arithmetic * minimize number of calls random number generator without expensive * calculations. class similar in operation * {@code securerandom.nextint(int)} method defined in java se. * * @author owlstead */ public final class jcsecurerandom { private static final short short_size_bytes = 2; private static final short start = 0; private final randomdata rnd; private final byte[] buf; /** * constructor uses given source of random bytes. 2 byte * buffer transient buffer generated cleared on deselect. * * @param rnd * source of random bytes */ public jcsecurerandom(final randomdata rnd) { this.rnd = rnd; this.buf = jcsystem.maketransientbytearray(short_size_bytes, jcsystem.clear_on_deselect); } /** * generates single short random value in range of 0 * (inclusive) given parameter n (exclusive). * * @param n * upper bound of random value, must positive * (exclusive) * @return random value in range [0..n-1] */ public short nextshort(final short n) { final short sn = (short) (n - 1); short bits, val; { bits = next15(); val = (short) (bits % n); } while ((short) (bits - val + sn) < 0); return val; } /** * generates single byte random value in range of 0 (inclusive) * given parameter n (exclusive). * * @param n * upper bound of random value, must positive * (exclusive) * @return random value in range [0..n-1] */ public byte nextbyte(final byte n) { if ((n & -n) == n) { return (byte) ((n * next7()) >> 7); } final byte sn = (byte) (n - 1); byte bits, val; { bits = next7(); val = (byte) (bits % n); } while ((byte) (bits - val + sn) < 0); return val; } /** * generates 15 bits 2 bytes setting highest bit zero. * * @return positive valued short containing 15 bits of random */ private short next15() { this.rnd.generatedata(this.buf, start, short_size_bytes); return (short) (util.getshort(this.buf, start) & 0x7fff); } /** * generates 7 bits 1 byte setting highest bit zero. * * @return positive valued byte containing 7 bits of random */ private byte next7() { this.rnd.generatedata(this.buf, start, short_size_bytes); return (byte) (this.buf[start] & 0x7f); } }
Comments
Post a Comment