Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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.

like image 944
tsh Avatar asked Dec 15 '22 04:12

tsh


2 Answers

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);
like image 143
Shaun Webb Avatar answered Dec 23 '22 16:12

Shaun Webb


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
like image 39
cfrick Avatar answered Dec 23 '22 16:12

cfrick