3
votes

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

1
The error message is clear, I think? ToHexString takes an int, but you're passing it a string. - Oliver Charlesworth
After converting into integer. import org.apache.commons.lang.RandomStringUtils; def randomhex = RandomStringUtils.randomNumeric(16).toInteger(); log.info randomhex def result = Integer.toHexString(randomhex); log.info result. It throw error - 'java.lang.NumberFormatException: For input string: "0192171878046802" error at line: 2' - rAJ

1 Answers

5
votes

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()