Merge pull request #496 from slisaasquatch/better-hex-2

More efficient hex generation
This commit is contained in:
Ricky Yim
2020-07-06 18:21:11 +10:00
committed by GitHub
@@ -60,11 +60,18 @@ public class RandomService {
}
public String hex(int length) {
char[] hexValues = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
StringBuilder hexString = new StringBuilder();
for(int i = 0; i < length; i++) {
hexString.append(hexValues[nextInt(hexValues.length)]);
if (length <= 0) {
return ""; // Keep the existing behavior instead of throwing an error.
}
return hexString.toString();
final char[] hexChars = new char[length];
for (int i = 0; i < length; i++) {
final int nextHex = nextInt(16);
if (nextHex < 10) {
hexChars[i] = (char) ('0' + nextHex);
} else {
hexChars[i] = (char) ('A' + nextHex - 10);
}
}
return new String(hexChars);
}
}