我正在尝试生成 16 位随机十六进制数。
import org.apache.commons.lang.RandomStringUtils;
def randomhex = RandomStringUtils.randomNumeric(16);
log.info randomhex
def result = Integer.toHexString(randomhex);
log.info result
预期 :结果应该是随机的 16 位十六进制数。
例如:328A6D01F9FF12E0
实际 :
groovy.lang.MissingMethodException:无方法签名:静态 java.lang.Integer.toHexString() 适用于参数类型:(java.lang.String) 值:[3912632387180714] 可能的解决方案:toHexString(int), toString() , toString(), toString(), toString(int), toString(int, int) 第 9 行错误
最佳答案
需要 64 位来存储 16 位十六进制数,这比 Integer 支持的要大。可以使用 Long 代替(Java 8 中添加了 toUnsignedString
方法):
def result = Long.toUnsignedString(new Random().nextLong(), 16).toUpperCase()
另一种可能的方法是生成从 0 到 16 的 16 个随机整数,并将结果连接到一个字符串中。
def r = new Random()
def result = (0..<16).collect { r.nextInt(16) }
.collect { Integer.toString(it, 16).toUpperCase() }
.join()
另一种方法是利用随机 UUID 并从中获取最后 16 位数字。
def result = UUID.randomUUID()
.toString()
.split('-')[-1..-2]
.join()
.toUpperCase()
关于groovy - 使用 Groovy 脚本生成随机的 16 位十六进制数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47672143/