1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package org.hipparchus.random;
24
25 import org.hipparchus.exception.LocalizedCoreFormats;
26 import org.hipparchus.exception.MathIllegalArgumentException;
27
28
29
30
31
32 abstract class IntRandomGenerator extends BaseRandomGenerator {
33
34
35 @Override
36 public abstract int nextInt();
37
38
39 @Override
40 public boolean nextBoolean() {
41 return (nextInt() >>> 31) != 0;
42 }
43
44
45 @Override
46 public double nextDouble() {
47 final long high = ((long) (nextInt() >>> 6)) << 26;
48 final int low = nextInt() >>> 6;
49 return (high | low) * 0x1.0p-52d;
50 }
51
52
53 @Override
54 public float nextFloat() {
55 return (nextInt() >>> 9) * 0x1.0p-23f;
56 }
57
58
59 @Override
60 public long nextLong() {
61 return (((long) nextInt()) << 32) | (nextInt() & 0xffffffffL);
62 }
63
64
65 @Override
66 public void nextBytes(byte[] bytes) {
67 nextBytesFill(bytes, 0, bytes.length);
68 }
69
70
71 @Override
72 public void nextBytes(byte[] bytes, int start, int len) {
73 if (start < 0 ||
74 start >= bytes.length) {
75 throw new MathIllegalArgumentException(LocalizedCoreFormats.OUT_OF_RANGE_SIMPLE,
76 start, 0, bytes.length);
77 }
78 if (len < 0 ||
79 len > bytes.length - start) {
80 throw new MathIllegalArgumentException(LocalizedCoreFormats.OUT_OF_RANGE_SIMPLE,
81 len, 0, bytes.length - start);
82 }
83
84 nextBytesFill(bytes, start, len);
85 }
86
87
88
89
90
91
92
93
94
95
96
97
98
99 private void nextBytesFill(byte[] bytes, int offset, int len) {
100 int index = offset;
101
102
103
104 final int indexLoopLimit = index + (len & 0x7ffffffc);
105
106
107 while (index < indexLoopLimit) {
108 final int random = nextInt();
109 bytes[index++] = (byte) random;
110 bytes[index++] = (byte) (random >>> 8);
111 bytes[index++] = (byte) (random >>> 16);
112 bytes[index++] = (byte) (random >>> 24);
113 }
114
115 final int indexLimit = offset + len;
116
117
118 if (index < indexLimit) {
119 int random = nextInt();
120 while (true) {
121 bytes[index++] = (byte) random;
122 if (index < indexLimit) {
123 random >>>= 8;
124 } else {
125 break;
126 }
127 }
128 }
129 }
130 }