tsh tsh - 2 months ago 27x
Groovy Question

Convert integer to hex string in Groovy

I'm new to Groovy. When I want convert some integer number to hex string, I have tried codes like this:


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?



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()


For numbers larger than the maximum value of long (9223372036854775807) the BigInterger datatype can be used.

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