在 Groovy 中将整数转换为十六进制字符串

Convert integer to hex string in Groovy

我是 Groovy 的新手。当我想将一些整数转换为十六进制字符串时,我尝试过这样的代码:

theNumber.toString(16)

就像我在 Java脚本中所做的那样。 (Groovy 就像另一种脚本语言看起来类似于 Java,对吧?)

但是上面的代码并没有像我预期的那样工作。当数字很大时,结果正确;但大多数时候,它只是 return 16.

println(256.toString(16)) // 16
println(36893488147419103232.toString(16)) // 20000000000000000

我很困惑为什么 Groovy 行为如此奇怪。谁能帮我解释一下?而且,将整数转换为十六进制字符串的最佳方法是什么?

谢谢。

Java 不是 Java 脚本。 Groovy 是为 Java 平台构建的语言。 Java 代码也可以直接与 Groovy 一起使用。所以你可以使用 .toHexString()

Integer.toHexString(256) 
Long.toHexString(28562)

对于大于 long 最大值 (9223372036854775807) 的数字,可以使用 BigInteger 数据类型。

String bigInt = new BigInteger("36893488147419103232").toString(16);

你调用的是静态 toString(int) 来自例如Integerdocs:

public static String toString(int i)

Returns a String object representing the specified integer. The argument is converted to signed decimal representation and returned as a string, exactly as if the argument and radix 10 were given as arguments to the toString(int, int) method.

例如:

groovy:000> Integer.toString(16)
===> 16

所以你想要的是:

groovy:000> Integer.toString(256,16)
===> 100