groovy - 使用 Groovy 脚本生成随机的 16 位十六进制数

标签 groovy hex soapui

我正在尝试生成 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/

相关文章:

grails - 我可以在 Grails 的接口(interface)类中使用 JAXRS 注释(例如 @Produces)吗

Java阅读POST,奇怪的十六进制解释

web-services - 通用 SOAP 客户端工具

java - 如何在 Gmaven 中转义 Java 泛型?

grails - 在 Grails Controller 中对父子进行排序

javascript - Unicode 代理项对和 String.fromCodePoint() — JavaScript

WCF web 服务 : HTTP/1. 1 400 发送大输入时的错误请求

java - 执行 psexec 并输出到本地主机上的文件

c++ - 在 C++ 中将十六进制字符串转换为字节