我正在尝试生成 16 位随机十六进制数。
import org.apache.commons.lang.RandomStringUtils;
def randomhex = RandomStringUtils.randomNumeric(16);
log.info randomhex
def result = Integer.toHexString(randomhex);
log.info result
Run Code Online (Sandbox Code Playgroud)
预期:结果应为随机 16 位十六进制数。例如:328A6D01F9FF12E0
实际:groovy.lang.MissingMethodException:没有方法签名:static java.lang.Integer.toHexString() 适用于参数类型:(java.lang.String) 值:[3912632387180714] 可能的解决方案:toHexString(int)、toString ()、toString()、toString()、toString(int)、toString(int, int) 错误位于第 9 行
存储 16 位十六进制数需要 64 位,这超出了 Integer 支持的大小。可以使用 Long 来代替(该toUnsignedString方法是在 Java 8 中添加的):
def result = Long.toUnsignedString(new Random().nextLong(), 16).toUpperCase()
Run Code Online (Sandbox Code Playgroud)
另一种可能的方法是生成 0 到 16 之间的 16 个随机整数,并将结果连接到一个字符串中。
def r = new Random()
def result = (0..<16).collect { r.nextInt(16) }
.collect { Integer.toString(it, 16).toUpperCase() }
.join()
Run Code Online (Sandbox Code Playgroud)
另一种方法是利用随机 UUID 并从中获取最后 16 位数字。
def result = UUID.randomUUID()
.toString()
.split('-')[-1..-2]
.join()
.toUpperCase()
Run Code Online (Sandbox Code Playgroud)