I'm new to Groovy. When I want convert some integer number to hex string, I have tried codes like this:
theNumber.toString(16)
as what I did in JavaScript. (Groovy is just like yet another script language looks similar to Java, right?)
But the code above not work as my expected. When the number is very large, the result is correct; but most of the time, it just return 16.
println(256.toString(16)) // 16
println(36893488147419103232.toString(16)) // 20000000000000000
I'm confused why Groovy behavior such strange. Could anyone help me to explain this? And, what is the best way to convert integer number to hex string?
Thanks.
Java is not JavaScript. Groovy is a language built for the Java platform. Java code also works directly with Groovy. So you can use .toHexString()
Integer.toHexString(256)
Long.toHexString(28562)
For numbers larger than the maximum value of long (9223372036854775807) the BigInteger datatype can be used.
String bigInt = new BigInteger("36893488147419103232").toString(16);
What you are calling is the static toString(int)
from e.g. Integer
. docs:
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.
E.g.:
groovy:000> Integer.toString(16)
===> 16
So what you want is:
groovy:000> Integer.toString(256,16)
===> 100
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With