I am trying to Generate 16 digit random HEX number.
import org.apache.commons.lang.RandomStringUtils;
def randomhex = RandomStringUtils.randomNumeric(16);
log.info randomhex
def result = Integer.toHexString(randomhex);
log.info result
Expected : The result should be random 16 digit HEX number. e.g : 328A6D01F9FF12E0
Actual : groovy.lang.MissingMethodException: No signature of method: static java.lang.Integer.toHexString() is applicable for argument types: (java.lang.String) values: [3912632387180714] Possible solutions: toHexString(int), toString(), toString(), toString(), toString(int), toString(int, int) error at line: 9
64 bits are needed to store a 16-digit hex number, which is bigger than Integer supports. A Long could be used instead (the toUnsignedString method was added in Java 8):
def result = Long.toUnsignedString(new Random().nextLong(), 16).toUpperCase()
Another potential approach is to generate 16 random integers from 0 to 16, and join the results into a String.
def r = new Random()
def result = (0..<16).collect { r.nextInt(16) }
.collect { Integer.toString(it, 16).toUpperCase() }
.join()
Yet another approach is to leverage a random UUID and just grab the last 16 digits from that.
def result = UUID.randomUUID()
.toString()
.split('-')[-1..-2]
.join()
.toUpperCase()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With